如何先执行一个承诺,然后移动到 JavaScript 中的下一条语句

How to execute a promise first and then move to the next statement in JavaScript

我想做的是等待第二个承诺完成,连接数据,即 data = data.concat(items),然后递增计数,使循环 运行 指定次数。都写在AngularJS.

DataService.getSomeData().then(function(data) {
  let count = 1;
  while (count < 3) {
    if (someCondition) { // It evaluates to true

      // Second Promise
      DataService.getUserData().then(function(items) {
        data = data.concat(items); // --------> this should run before incrementing the count
      });

      count++;
    }
    $scope.myData = data;
  }
});

谢谢!

@Aleksey Solovey 已经提到了使用 $q.all() 的解决方案,还有另一种递归方法可以使用。

DataService.getSomeData().then(function(data) {
  getUserDataRecursion(data,0).then(result=>{
    $scope.myData = result;
  }).catch(error=>{
    console.log("error handle ",error)
  })
});


getUserDataRecursion(data,count){
  return new Promise((resolve,reject)=>{
    if(count<3){
      if (someCondition){
        DataService.getUserData().then((items) {
          data = data.concat(items);
          count++;
          getUserDataRecursion(data,count),then(()=>{
            resolve(data);
          })
        });
      }else{
        resolve(data);
      }
    }else{
      resolve(data);
    }
  })
}

保持 api 返回承诺 - 它最容易处理且最可预测...

  DataService.getSomeData()
    .then(someData => {
        let count = 1;
        const promises = [];

        while (count < 3) {
            if (someCondition) { // It evaluates to true
                promises.push(DataService.getUserData());
                count++;
            }
        }

        return $q.all(promises)
            .then(data => data.reduce((memo, data) => memo.concat(data), someData));
    })
    .then(data => $scope.myData = data);