使用setTimeout,我應該在foreach完成後使用什麼?節點js foreach功能
app.post('/grid', function(req, res){
getResults(req.body.idarray, function(callback){
res.send(callback);
});
});
function getResults(userIds, callback) {
var totalresult = [];
userIds.forEach(function (user) {
sequence
.then(function (next) {
db.query('SELECT given FROM books WHERE user_id = ?', [user.userId], function (err2, result) {
if (err2) throw err2;
next(err, result);
});
})
.then(function (next, err, books) {
db.query('SELECT received FROM encycs WHERE user_id = ?', [user.userId], function (err3, result2) {
if (err3) throw err3;
next(err, result2, books);
});
})
.then(function (next, err, books, encycs) {
Calculation(books, encycs, function (cb) {
totalresult.push(cb);
});
next();
});
});
setTimeout(function() {
console.log(totalresult); // output ok.
return callback(totalresult); // returning as expected
}, 2000);
}
我不知道什麼totalresult.length是。所以我無法檢查長度。
檢查你是否達到第三。然後聲明。如果沒有,那麼你需要檢查它。 – QuestionAndAnswer
我不明白。你能舉一個小例子來說明如何達成一個.then聲明嗎? – user3325207
你有三個案例。首先選擇* books *,然後選擇* enycycs *,第三個語句執行一些計算並將結果推送到totalresult數組中。據我所知,這是你填充它的唯一地方。第二件事情要檢查,你沒有在回調的成功分支中的任何地方返回你的totalresult數組,只有在出錯時。所以,檢查你是否真的填充數組,如果我看到正確的你沒有返回它,因此,只要你需要返回它。 – QuestionAndAnswer