我是节点js中的新手,并且遇到了带有db返回的回调控制流的问题。
我想要的是以下顺序:
console.log('>>>>>>> first log in F1 >>>>>>');
console.log('>>>>>>> second log in F1 >>>>>>');
console.log('>>>>>>> first log in F2 >>>>>>');
console.log('>>>>>>> second log in F2 >>>>>>');
console.log('>>>>>>> first log in F3 >>>>>>');
console.log('>>>>>>> second log in F3 >>>>>>');
console.log('>>>>>>> first log in F4 >>>>>>');
console.log('>>>>>>> second log in F4 >>>>>>');
console.log('>>>>>>> third log in F4 >>>>>>');
console.log('finished ');
但我没有按顺序进行。代码如下所示:
F1(req).then(function(result){
return F2(result);
}).then(function(result){
return F3(result);
}).then(function(result){
return F4(result);
}).then(function(result){
console.log('finished ');
})
var F1 = function(req) {
return new Promise(function(resolve, reject) {
console.log('>>>>>>> first log in F1 >>>>>>');
var result = {};
result.emailId = req.body.emailId;
common.db.collection('document1').findOne({email: req.body.emailId}, function (error, document1object) {
console.log('>>>>>>> second log in F1 >>>>>>');
});
resolve(result);
});
};
var F2 = function(result) {
console.log('>>>>>>> first log in F2 >>>>>>');
return new Promise(function(resolve, reject) {
common.db.collection('document2').findOne({email: result.emailId}, function (err, document2object) {
console.log('>>>>>>> second log in F2 >>>>>>');
result.value1 = document2object._id;
});
resolve(result);
});
};
var F3 = function(result) {
console.log('>>>>>>> first log in F3 >>>>>>');
return new Promise(function(resolve, reject) {
common.db.collection('document3').insertOne({email: result.emailId}, function (errr, document3object) {
console.log('>>>>>>> second log in F3 >>>>>>');
result.value2 = document3object.insertedId;
});
resolve( result);
});
};
var F4 = function(result) {
console.log('>>>>>>> first log in F4 >>>>>>');
return new Promise(function(resolve, reject) {
client.post("urlPart1"+result.value2+"urlPart2",
args, function (data, response) {
console.log('>>>>>>> second log in F4 >>>>>>');
});
console.log('>>>>>>> third log in F4 >>>>>>');
resolve( result);
});
};
提前谢谢你:)
答案 0 :(得分:0)
因为......异步。
您的请求会同时进行所有评估,因此您无法按照所需的顺序获取日志。如果你想要一个特定的订单,你必须在最后一个请求完成后开始下一个请求,即在前一个请求的回调函数中。