Node.js的:如何运行code顺序异步 [英] Node.js: How to run asynchronous code sequentially
问题描述
我有code的这个块
User.find({}, function(err, users) {
for (var i = 0; i < users.length; i++) {
pseudocode
Friend.find({
'user': curUser._id
}, function(err, friends) * * ANOTHER CALLBACK * * {
for (var i = 0; i < friends.length; i++) {
pseudocode
}
console.log("HERE I'm CHECKING " + curUser);
if (curUser.websiteaccount != "None") {
request.post({
url: 'blah',
formData: blah
}, function(err, httpResponse, body) { * * ANOTHER CALLBACK * *
pseudocode
sendMail(friendResults, curUser);
});
} else {
pseudocode
sendMail(friendResults, curUser);
}
});
console.log("finished friend");
console.log(friendResults);
sleep.sleep(15);
console.log("finished waiting");
console.log(friendResults);
}
});
有一对夫妇异步事情发生在这里。对于每一个用户,我想找到自己的朋友有关,并将其Concat的一个变量。然后,我要检查,如果该用户有一个网站账号,如果是这样,做一个POST请求并有抓住一些信息。唯一的一点是,这一切正在发生无序自code未等待回调结束。我一直在使用睡眠,但这并不解决任何因为它仍然混乱的问题。
There's a couple asynchronous things happening here. For each user, I want to find their relevant friends and concat them to a variable. I then want to check if that user has a website account, and if so, make a post request and grab some information there. Only thing is, that everything is happening out of order since the code isn't waiting for the callbacks to finish. I've been using a sleep but that doesn't solve the problem either since it's still jumbled.
我看着成异步,但这些功能相互交织,并没有真正分开,所以我不知道它会如何与工作异步两种。
I've looked into async, but these functions are intertwined and not really separate, so I wasn't sure how it'd work with async either.
任何建议得到这code按顺序运行?
Any suggestions to get this code to run sequentially?
谢谢!
推荐答案
我preFER承诺模块为q的 https://www.npmjs.com/package/promise 因为它的简单
I prefer the promise module to q https://www.npmjs.com/package/promise because of its simplicity
var Promises = require('promise');
var promise = new Promises(function (resolve, reject) {
// do some async stuff
if (success) {
resolve(data);
} else {
reject(reason);
}
});
promise.then(function (data) {
// function called when first promise returned
return new Promises(function (resolve, reject) {
// second async stuff
if (success) {
resolve(data);
} else {
reject(reason);
}
});
}, function (reason) {
// error handler
}).then(function (data) {
// second success handler
}, function (reason) {
// second error handler
}).then(function (data) {
// third success handler
}, function (reason) {
// third error handler
});
正如你所看到的,你可以继续这样下去。您也可以从异步处理程序返回简单的值,而不是承诺,然后这些将简单地传递给然后
回调。
这篇关于Node.js的:如何运行code顺序异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!