nodeJS:Promise在循环结束之前执行,callback堆栈

我正在使用promise来创buildresult array Postman响应; 然而,在forEach循环完成之前, resolve()被调用,而resolve()在forEach循环之外。 我觉得这是由于callback堆栈function。

考虑到callback stack ,在forEach循环完成执行之后,如何执行resolve()


(server.js):

 logServer.post('/log/asset/audit/', function(req,res){ console.log('--- starting log/asset/audit'); logDB.collection('logs') .find({"transaction.assetName" : assetName, "transaction.assetOwner" : assetOwner}) .toArray( (err, result) => { let token = JSON.parse(JSON.stringify(self_jwt_body)); var JSONPromise = new Promise((resolve, reject) => { //initialization result.forEach(function(element, index, array) { console.log('- before request.post'); request.post({ url: `${dc_link}/audit`, //includes dc_IP, dc_port and /audit headers: { "jwt": jwt.sign(token, jwtSecret) } }, function(error,response,body) { console.log('path 0'); let parseBody = JSON.parse(body); console.log('path 3'); result[0].transaction.signature = parseBody.additionalData; console.log('result: ', result); //**HERE }); }); //**HERE resolve(); }; //end callback JSONPromise.then(() => { //finalization //**HERE respondWithJSON(200, req.body.result, req.body.description, res, result); console.log('end log/asset/audit'); }; }); }); 

您在任何响应到达之前调用resolve()

您需要将request()包装在一个返回promise(一个请求)的函数中,然后写入

 Promise.all(result.map(e => requestPromise(...))) 

等待所有这些承诺。

应该更接近你所需要的。

 logServer.post('/log/asset/audit/', function (req, res) { console.log('--- starting log/asset/audit'); logDB.collection('logs') .find({ "transaction.assetName": assetName, "transaction.assetOwner": assetOwner }) .toArray((err, result) => { let token = JSON.parse(JSON.stringify(self_jwt_body)); var JSONPromise = new Promise((resolve, reject) => { //initialization let async_result = result.map(function (element, index, array) { console.log('- before request.post'); return new Promise((resolve,reject)=>{ request.post({ url: `${dc_link}/audit`, //includes dc_IP, dc_port and /audit headers: { "jwt": jwt.sign(token, jwtSecret) } }, function (error, response, body) { console.log('path 0'); let parseBody = JSON.parse(body); console.log('path 3'); result[0].transaction.signature = parseBody.additionalData; console.log('result: ', result); resolve(); //**HERE }); }); }); //**HERE return Promise.all(async_result); }); //end callback JSONPromise.then(() => { //finalization //**HERE respondWithJSON(200, req.body.result, req.body.description, res, result); console.log('end log/asset/audit'); }); }); });