我想在async 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
答案 0 :(得分:4)
将 map 改为Promise,而不是使用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();
});
答案 1 :(得分:2)
您可以创建一个承诺数组,然后使用Promise.all
侦听所有完成。
const promises = [];
myPosts.forEach(function(post) {
const promise = new Promise((resolve) => {
getPostAuthor(post.authorID, function(postAuthor) {
post.author = postAuthor;
resolve(); // complete the current promise
}
});
promises.push(promise);
});
Promise.all(promises).then(() => {
res.render('index', {
posts: myPosts
});
res.end();
});
答案 2 :(得分:0)
您可以通过2种方式执行此操作,您可以使用Promise或使用计数方法。
计数方法:
var numComplete = 0;
var done = function() {
if(numComplete >= myPosts.length) {
// Code to run once finished
}
};
myPosts.forEach(function(post) {
getPostAuthor(post.authorID, function(postAuthor) {
post.author = postAuthor;
numComplete++;
done();
}
});
答案 3 :(得分:0)
您可以使用像Async这样的第三方库。
示例:
$data = array (
$_POST ['vorname'],
$_POST ['nachname'],
$_POST ['ort'],
$_POST ['plz'],
$_POST ['strasse']
);
if(!empty(array_map('trim', array_filter($data)))) {
$fp = fopen('file.csv', 'a+');
fputcsv($fp, $data);
fclose($fp);
}
您的代码应如下所示:
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.');
}
});
答案 4 :(得分:0)
您可以使用test("^A"; "i")
尝试async/await
。
for loop

答案 5 :(得分:0)
使用async.eachOf迭代数组并应用异步函数:
async.eachOf(myPosts, function(post, it, callback){
// apply async function on each element
getPostAuthor(post.authorID, function(postAuthor) {
post.author = postAuthor;
return callback();
});
}, function(err){
// final callback when flow is finished
res.render('index', {
posts: myPosts
});
return res.end();
});