【发布时间】:2015-01-06 11:49:00
【问题描述】:
我在使用 Node JS 进行同步调用时遇到问题。这是我的问题:
我有以下代码:
async.doWhilst(function(callback) {
//some code
callback();
}, function() {
//make a database call and based on the results I should
//return true to continue looping or false to stop here
}, function(err) {
//do some things when the loop finishes
})
问题是调用数据库时是异步调用,循环在返回正确值之前继续。
非常感谢您的 cmets,我已经通过将数据库调用移动到循环代码来解决问题,如下所示:
var results = []
async.doWhilst(function(callback) {
//some code
sequelize.query('some query').success(function(result) {
results = result;
callback();
});
}, function() {
//use the results variable that is fetched from the database
//return true to continue looping or false to stop here
}, function(err) {
//do some things when the loop finishes
})
【问题讨论】:
-
测试函数应该是同步的,尝试在其中引入异步代码和某种等待循环会真的,真的,真的不好
-
我试图让它同步,但我不知道如何,问题是数据库调用取决于循环代码中的变量更改
-
您不能使异步操作同步运行。你就是不能。它与同步操作的时间不同,无法做到。
-
非常感谢@JanAagaardMeier,您的评论给了我将数据库调用移至循环代码的提示。我将正确回答我所做的事情。
标签: node.js asynchronous sequelize.js async.js