gpt4 book ai didi

javascript - 如何在 node.js 中完成异步函数后运行函数?

转载 作者:数据小太阳 更新时间:2023-10-29 06:04:56 25 4
gpt4 key购买 nike

我想在我的 之后运行代码forEach 循环。

myPosts.forEach(function(post) {
getPostAuthor(post.authorID, function(postAuthor) {
post.author = postAuthor;
}
});

res.render('index', {
posts: myPosts
});
res.end();

在上面的代码中,首先运行 res.render,然后运行 ​​forEach 填充 post.author

最佳答案

与其使用 forEach 迭代,不如映射到 Promise,然后使用 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();

});

关于javascript - 如何在 node.js 中完成异步函数后运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45571621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com