Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/414.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ForEach(内部包含异步函数)完成后的回调_Javascript_Asynchronous_Foreach_Callback_Sync - Fatal编程技术网

Javascript ForEach(内部包含异步函数)完成后的回调

Javascript ForEach(内部包含异步函数)完成后的回调,javascript,asynchronous,foreach,callback,sync,Javascript,Asynchronous,Foreach,Callback,Sync,我有一个.forEach循环,其中包含一个异步函数,我的代码正在循环完成之前执行回调() 有没有办法让它完成循环,然后转到我的callback()。 这是我的密码: var transactions = []; t.transactions.forEach(function(id){ client.query('SELECT * FROM transactions WHERE id = $1;', [id], function(err, result) { if(!err

我有一个.forEach循环,其中包含一个异步函数,我的代码正在循环完成之前执行回调() 有没有办法让它完成循环,然后转到我的callback()。
这是我的密码:

var transactions = [];
t.transactions.forEach(function(id){
    client.query('SELECT * FROM transactions WHERE id = $1;', [id], function(err, result) {
        if(!err){
            transactions.push({from : result.rows[0].from, to : result.rows[0].to, amount : result.rows[0].amount, time : result.rows[0].ct, message : result.rows[0].message, id : result.rows[0].id});
        }
    });
});
callback(transactions);
return done();

使用的索引参数测试您是否在上一个事务中:

var transactions = [];
t.transactions.forEach(function(id, idx){
    client.query('SELECT * FROM transactions WHERE id = $1;', [id], function(err, result) {
        if(!err){
            transactions.push({from : result.rows[0].from, to : result.rows[0].to, amount : result.rows[0].amount, time : result.rows[0].ct, message : result.rows[0].message, id : result.rows[0].id});
        }
        // If this is the last transaction, do the callback
        if(idx === t.transactions.length - 1) callback(transactions);
    });
});

因为每个事务只有一个查询,所以可以将测试放在查询的回调中。

非常感谢!很抱歉,我的回复太晚了。我已经两天没收到回复了。