2017-02-20 34 views
0

呼叫ID从MongoDB中有回调函数我需要帮助有关与MongoDB的node.js的Asynchronus电话,我需要调用同步方法进行数据

var GetID = function (nameval, callback) { 
    console.log(nameval); 
    console.log("munesh hello"); 
    GenerateID.find({ "id_name": nameval }, { 
     "id_code": 1, 
     "id_value": 1, "_id": 0 
    }, function (err, genvalue) { 
     if (err) { 
      console.log('hello'); 
     } 
     else { 
      if (genvalue === null) { 
       callback(err, false); 
      } 
      else { 
       callback(err, true); 
      } 
     } 
     console.log(genvalue); 
    }); 
}; 

的进一步处理,并调用上面的方法,所以我们需要
所以我们需要编号从GenerateID.GetID并做我们自己的工作。

var region_id = GenerateID.GetID(name, function (error, result) { 
    if (error) { 
     console.log("getting any error"); 
    } else { 
     console.log(region_id); 
     if (!result) { 
      console.log('data is not coming'); 

     } else { 
      console.log('data is coming'); 
     } 
    } 
});    
+0

使用async.js用于控制流 –

回答

0

您有许多问题。在第一段代码中,您需要在调用回调函数时传递实际值。

第二,你需要设置region_id = result。

理想情况下,您可以使用promise来做到这一点,如下所示。


var GetID = function(nameval){ 
    return new Promise((resolve,reject) => { 
     console.log(nameval); 
     console.log("munesh hello"); 

     GenerateId.find({ "id_name" : nameval },{"id_code":1 , "id_value":1, "_id":0}, 
      function(err , genvalue) { 

       console.log(genvalue); 

       if (err) { 
        console.log('hello'); 
        return reject() 
       } 
       if (genvalue == null) { return resolve(false); } 
       return resolve(genValue); 
      }); 
    }); 
} 

var GetIDPromise = GenerateId.GetID(name); 

GetIDPromise.then(
     genValue => { 
      if (genValue == false){ 
       console.log('data is not coming'); 

       // handle region id not being available. Perhaps return and show an error    
      }else{ 
      var region_id = genValue; 
      // continue execution and use region id. 
      } 
     }, 
     error => { 
      console.log("getting any error"); 
     } 
    )