Correct way to write loops for promise.

后端 未结 13 1884
猫巷女王i
猫巷女王i 2020-11-22 15:20

How to correctly construct a loop to make sure the following promise call and the chained logger.log(res) runs synchronously through iterat

13条回答
  •  一向
    一向 (楼主)
    2020-11-22 15:43

    I'd make something like this:

    var request = []
    while(count<10){
       request.push(db.getUser(email).then(function(res) { return res; }));
       count++
    };
    
    Promise.all(request).then((dataAll)=>{
      for (var i = 0; i < dataAll.length; i++) {
    
          logger.log(dataAll[i]); 
      }  
    });
    

    in this way, dataAll is an ordered array of all element to log. And log operation will perform when all promises are done.

提交回复
热议问题