我有情景。我想在mongodb中更新数据后执行循环的地方。这样的意思:

var i = 0;
while (i< 5) {
    attendanceDataModel.update(query, condition).exec(function(error, data) {
        if (error) {
            console.log("Error @ 168 line in app.js File : \n" + err + "\n");
            i++;
        } else {
            if (data.length <= 0) {
                console.log("No Records Matched.");
                i++;
            } else {
                console.log(currEmpId + " : successfully Logged Out ! :-)" + data + "\n");
                updateRecordNumber(currRecordNumber);
                i++;  //wrong because it increases the value before updating in DB.
            }
        }
    });
}

var updateRecordNumber = function(currRecordNumber) {

    var condition = { deviceLogId: parseInt(currRecordNumber) };

    lastDeviceLogIdModel.update({}, condition).exec(function(error, data) {
        if (error) {
            console.log("Error @ 213 line in app.js File : \n" + err + "\n");
        } else {
            if (data.length <= 0) {
                console.log("No Records Matched." + "\n");
            } else {
                console.log(currRecordNumber + " : DeviceLogId successfully Updated ! :-)");
      // I want to increase value of i here after updation in database
            }
        }
    });
}


现在,我想在函数updateRecordNumber成功更新后增加变量i的值

最佳答案

最简单的方法是像var updateRecordNumber = function(currRecordNumber, callback)这样的更改函数,然后更改调用:updateRecordNumber(currRecordNumber, function(){ i++ });

但是我认为使用某些控制流方法是一个更好的解决方案,例如PromisesAsync.js

附言当然,您必须更改函数的主体:

var updateRecordNumber = function(currRecordNumber, callback) {
// all your async stuff
  callback();
}

关于javascript - 如何使循环等待node.js中的回调?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36305499/

10-10 02:09