简体   繁体   English

。然后Promise.all结果永远不会执行

[英].then of Promise.all result never executes

I am trying to use Promise.all and map instead of the forEach loop so the task can be asynchronous. 我正在尝试使用Promise.allmap而不是forEach循环,以便任务可以异步进行。 All of the promises in the Promise.all array get executed and are resolved. Promise.all数组中的所有promise都将执行并得到解决。 The code looks like this: 代码如下:

loadDistances() {
    //return new Promise((resolve, reject) => {
      let rrr;
      let arr = [];
      this.geolocation.getCurrentPosition().then((resp) => {            
          // resp.coords.latitude
          rrr = resp;
          console.log(rrr + "              rrrrrrrrrrrrrrrrrrrrrrrrrr");

          setTimeout(() => {
            this.distancelist = this.af.list('/profiles/stylists');

            let x = 0;
            this.subscription6 = this.distancelist.subscribe(items => {

              let mapped = items.map((item) => {
                return new Promise(resolve => {
                  let rr;
                  //console.log(JSON.stringify(item) + "               *((*&*&*&*&^&*&*&*(&*(&*&*(&(&(&*(              :::" + x);
                  if(item.address == "") {
                    /*if(!item.picURL) {
                      item.picURL = 'assets/blankprof.png';
                    }*/
                    //arr.push({'pic':item.picURL, 'salon':item.username, 'distance':"No Address"});
                    //x++;
                  }
                  else {
                    console.log(item.address + " is the address empty??????");
                    this.nativeGeocoder.forwardGeocode(item.address)
                      .then((coordinates: NativeGeocoderForwardResult) => {
                        console.log("I AM IN THE GEOCODING ***&&*&*&*&*");
                          rr = this.round(this.distance(coordinates.latitude, coordinates.longitude, rrr.coords.latitude, rrr.coords.longitude, "M"), 1);
                          if(!item.picURL) {
                            item.picURL = 'assets/blankprof.png';
                          }
                          arr.push({'pic':item.picURL, 'salon':item.username, 'distance':rr});
                          console.log("push to the array of results");
                          //x++;
                          /*console.log(items.length + "         length   /    x:        " + x);
                          if(items.length - x == 1) {
                            console.log("getting resolved in geocoder ^&^&^&&^^&^&^&");
                            resolve(arr);
                          }*/
                          resolve();
                        }).catch(e => {
                          console.log(e.message + " caught this error");
                          /*x++;
                          if(items.length - x == 1) {
                            resolve(arr);
                          }*/
                          resolve();
                        })
                  }

                })
              });

              let results = Promise.all(mapped);
              results.then(() => {
                console.log(JSON.stringify(arr) + " :FOSIEJO:SFJ::EFIJSEFIJS:EFJS:IO THIS IODIOSJ:FDSIJ :DIS");
                arr.sort(function(a,b) {
                  return a.distance - b.distance;
                });

                this.distances = arr.slice();
              })

            });//);
          }, 1500)




      /*}).catch((error) => {
        this.diagnostic.switchToLocationSettings();
        console.log('Error getting location', error.message);
        resolve();
      });*/

    });


  }

The console output is: 控制台输出为:

[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:27]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:27]  console.log: push to the array of results 
[12:38:28]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:28]  console.log: push to the array of results 
[12:38:29]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:29]  console.log: push to the array of results 
[12:38:29]  console.log: I AM IN THE GEOCODING ***&&*&*&*&* 
[12:38:29]  console.log: push to the array of results 

The alternating messages make it seem like it worked and all of the promises got resolved. 交替出现的消息使它看起来像在起作用,所有的诺言都得到了解决。 But when I do Promise.all this line never happens in the console: 但是当我做Promise.all这行在控制台中永远不会发生:

console.log(JSON.stringify(arr) + " :FOSIEJO:SFJ::EFIJSEFIJS:EFJS:IO THIS IODIOSJ:FDSIJ :DIS");

So it is not reaching the then of the Promise.all results . 所以它是没有达到then的的Promise.all results

You have code paths that don't resolve, specifically: 您有无法解析的代码路径,特别是:

if(item.address == "") {
  /*if(!item.picURL) {
    item.picURL = 'assets/blankprof.png';
  }*/
  //arr.push({'pic':item.picURL, 'salon':item.username, 'distance':"No Address"});
  //x++;
}

It is very easy getting into deadlocks like @andy-gaskell pointed out when creating new Promises. 创建新的Promises时,陷入@@ andy-gaskell这样的僵局非常容易。 To avoid that you better do one of these; 为避免发生这种情况,您最好执行以下操作之一; All of these may throw an impossible error or return 1. 所有这些都可能引发不可能的错误或返回1。

function promiseWithTryCatch() {
  return new Promise((resolve, reject) => {
    try {
      let result;
      // your code

      resolve(result);
    }
    catch(ex) {
      reject(ex);
    }
  })
}

function promiseWithResolve() {
  return Promise.resolve()
    .then(() => {
      let result;
      // your code

      return result; 
    })
}

async function promiseWithAsync() {
  let result;
  // your code

  return result;
}

Replace the comment with your code and place the ending result into the variable result. 用您的代码替换注释,并将最终结果放入变量结果中。 If your code contains async code, you better make a new function with the same pattern and return that as the result, eg: result = [promise method] 如果您的代码包含异步代码,则最好使用相同的模式创建一个新函数并将其返回为结果,例如:result = [promise method]

  • The most scary one is "new Promise", if any code does not resolve or reject it will end in a "dead-lock", that's why it is important to have a try/catch. 最可怕的是“新的承诺”,如果任何代码无法解析或拒绝,它将以“死锁”结尾,这就是为什么尝试/捕获很重要的原因。
  • If you are using Promise.resolve() it will catch any errors inside .then but don't do any code outside .then, otherwise you have to catch exception and return a Promise.reject(new Error()) 如果您正在使用Promise.resolve(),它将在.then内部捕获任何错误,但不要在.then外执行任何代码,否则,您必须捕获异常并返回Promise.reject(new Error())
  • The safest is async function, since any "throw" will return a Promise.reject, and "return" will return a Promise.resolve 最安全的是异步函数,因为任何“ throw”都将返回Promise.reject,而“ return”将返回Promise.resolve

Play around with this example, but I had to comment out async/await since this snippet tool doesn't handle ES2016. 玩这个例子,但是我不得不注释掉异步/等待,因为这个片段工具不能处理ES2016。

 function nestedPromise(num) { return Promise.resolve(' myNestedValue is ' + num); } function promiseWithTryCatch() { return new Promise((resolve, reject) => { try { let mynumber = 2 + 5; nestedPromise(mynumber) .then((answer) => { resolve(answer.trim()); }) .catch(ex => { // error handling for async-code reject(ex); }) } catch(ex) { // error handling for sync-code reject(ex); } }) } function promiseWithResolve() { return Promise.resolve() .then(() => { let mynumber = 2 + 5; return nestedPromise(mynumber); }) .then((answer) => { // do something with the answer return answer.trim(); }) } /* async function promiseWithAsync() { let mynumber = 2 + 5; let answer = await nestedPromise(mynumber); return answer.trim(); } */ promiseWithTryCatch() .then(answer => console.log('promiseWithTryCatch result is ' + answer)) .catch(err => console.log('promiseWithAsync error is ' + err.message)); promiseWithResolve() .then(answer => console.log('promiseWithResolve result is ' + answer)) .catch(err => console.log('promiseWithResolve error is ' + err.message)); /* promiseWithAsync() .then(answer => console.log('promiseWithAsync result is' + answer)) .catch(err => console.log('promiseWithAsync error is ' + err.message)); */ 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM