2016-04-23 194 views
1
 Promise.all(function(){ 
    for(var numb in req.body) 
    { 

    console.log(numb+":"+req.body[numb]); 

    checkValue(numb,function(err,result){ 
     if(result) 
      { 
     console.log(result); 
     send[result]="true"; 
     console.log(send); 

      } 
     if(err) 
      {console.log(err+"not");} 
    }); 
    } 
}).then(res.json(send)); 

我想首先执行for循环,然后发回数据。我正在尝试使用promise.all,但我不确定它是否正确。有人能帮助我吗?承诺在node.js循环

+0

请格式化/缩进你的代码正确,使其可读。 – jfriend00

+0

您将一组承诺传递给'Promise.all()'。您不会将函数传递给'Promise.all()'。你所显示的代码中也没有异步操作,所以根本没有理由使用promise。你可以编写一个规则的循环。 – jfriend00

回答

9

如果您使用的承诺,通过执行以下操作检查this

你可以解决这个问题:

var promises = []; 

for(var numb in req.body) 
{ 
    promises.push(checkValue(numb)); 
} 

Promise.all(promises)  
.then(function(data){ /* do stuff when success */ }) 
.catch(function(err){ /* error handling */ }); 

function checkValue(numb){ 
return new Promise(function(resolve, reject){ 
    // place here your logic 
    // return resolve([result object]) in case of success 
    // return reject([error object]) in case of error 
});