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

时间:2017-11-28 16:24:41

标签: javascript node.js promise

我正在使用promise创建对result array邮递员的回复;但是,resolve()在forEach循环完成之前被调用,而resolve()在forEach循环之外。我觉得这是由于回调堆栈功能。

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

(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');
        };
   });
});

2 个答案:

答案 0 :(得分:2)

在任何回复到达之前,您正在呼叫resolve()

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

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

等待所有这些承诺。

答案 1 :(得分:0)

应该更接近你需要的东西。

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');
            });
        });
});