Nodejs如何访问函数外的回调变量?

时间:2017-05-17 12:47:14

标签: node.js callback

这是我的代码想要在call-function之外访问回调变量newID。我想使用具有自动递增id而不是默认对象

的批处理将批量数据插入mongodb
for (var i = 0; i < sizeOfResult; ++i) {
    var newKey = {};  //Main  json array 
    newKey = {
        date: result[i]['date'],  
        issue: result[i]['issue'],
        status: result[i]['status'] 
    };

    getNextSequenceValue("inventoryid",db, function(err, newID) {
        newKey["_id"] = newID;  <!-- try to add/assign callback variable(newID) into newKey  -->
    });
    console.log("newKey: %j", newKey);       <!-- but unable to get access callback variable(newID) here below-->
    batch.insert(newKey);
}

//这是我的召唤功能

function getNextSequenceValue(name,db,callback) {
    var ret = db.collection('counters_inv').findAndModify({ _id: name },null,{ $inc: { sequence_value: 1 } }, {new: true},
    function(err,doc )  {
        if(err){
        return callback(err)   // callback on error
    }
    callback(null, doc.value.sequence_value);  // callback on success

    });
}

2 个答案:

答案 0 :(得分:0)

看看这段代码,你只需要将变量放在外面就可以了:

let i = 1

function functionwithcallback(callback) {
    console.log(i)
    i++
    callback(i)
}

for (let j = 1; j <= 10; j++) {
    functionwithcallback(() => {
        if (j == 10)
            console.log('done')
    })
}

答案 1 :(得分:0)

我不确定总体目标是什么,但是你的newKey变量设置不正确的原因是因为它在设置变量之前已经执行了。在你的例子中,你的for循环将完全完成运行,开始一堆getNextSequenceValue()方法调用,最终会返回并运行回调代码。 它不会等待getNextSequenceValue函数在继续循环之前完成

解决方案:将console.log()batch.insert()移至回调中。

这是一个以正确顺序执行的示例。

var keys = [];

for (var i = 0; i < sizeOfResult; ++i) {
    var newKey = {
         date: result[i]['date'],
         issue: result[i]['issue'],
         status: result[i]['status']
    };

    getNextSequenceValue("inventoryid", db, function(err, newID) {
         newKey["_id"] = newID;

         keys.push(newKey);

         if (keys.length === sizeOfResult) {
             console.log("keys: %j", keys);  
             batch.insertAll(keys); 
         }
    });
}   

function getNextSequenceValue(name, db, callback) {
    db.collection('counters_inv').findAndModify({ _id: name }, null, { $inc: { sequence_value: 1 } }, {new: true}, 
    function(err,doc) {
        if(err){
           return callback(err);
        }
        callback(null, doc.value.sequence_value);
     });
}
相关问题