你可以使用一個第三方的lib像異步。
例子:
import each from 'async/each';
var elements = [1, 2, 3, 4, 5, 6];
each(elements, function(el, next) {
console.log('Processing element ' + el);
callAsyncFunction(next); //your async function should accept a callback
}, function(err){
//this is your ending function. It'll be called after all elements have been processed
if(err) {
console.log('A file failed to process');
} else {
console.log('Async processing is finished.');
}
});
您的代碼應該是這樣的:
each(myPosts, function(post, next) {
getPostAuthor(post.authorID, function(postAuthor) {
post.author = postAuthor;
next()
});
}, function(err) {
if (!err) {
res.render('index', {
posts: myPosts
});
res.end();
}
});
的forEach不是異步。 getPostAuthor是。 –
不,但我敢打賭'getPostAuthor()'是。 – jakerella
我的意思是forEach的函數 –