new*_*ent 5 javascript asynchronous callback node.js
我想在异步 forEach循环后运行代码。
myPosts.forEach(function(post) {
getPostAuthor(post.authorID, function(postAuthor) {
post.author = postAuthor;
}
});
res.render('index', {
posts: myPosts
});
res.end();
Run Code Online (Sandbox Code Playgroud)
在上面的代码中先运行res.render,然后forEach填充post.author
而是映射到承诺比用foreach迭代,然后使用Promise.all:
Promise.all(
myPosts.map(function(post) {
return new Promise(function(res){
getPostAuthor(post.authorID, function(postAuthor) {
post.author = postAuthor;
res(postAuthor);
});
});
})
).then(function(authors){
res.render('index', {
posts: myPosts
});
res.end();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4832 次 |
| 最近记录: |