2017-09-03 4 views
1

Ich versuche Promise.all und map anstelle der ForEach Schleife zu verwenden, so dass die Aufgabe asynchron sein kann. Alle Versprechen im Array Promise.all werden ausgeführt und aufgelöst. Der Code sieht wie folgt aus:.dann von Promise.all Ergebnis führt nie

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

    }); 


    } 

Die Konsolenausgabe ist:

[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 

Die alternierenden Nachrichten, die es scheinen, wie es gelöst war, habe all die Versprechungen. Aber wenn ich Promise.all tun diese Linie nie passiert, in der Konsole:

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

So ist es nicht die then des Promise.allresults erreichen.

+0

Oh mein Gott, was für ein Durcheinander dieser Code ist. Es macht so viele verschiedene Dinge. Aber um mit dem Aufräumen zu beginnen, wie lange beträgt die Auszeit von 1500ms? Und was ist das generell? denn 'this' scheint so ziemlich alles zu enthalten, von State über Submodule bis zu Utility-Funktionen wie' round() '. – Thomas

+0

und wenn Sie dazu bereit sind, schalten Sie Ihren Code auf async/erwarten und es wird viel sauberer zu lesen -> https://blog.mariusschulz.com/2016/12/09/typescript-2-1-async- erwarten-für-es3-es5 – Lostfields

+0

@Thomas danke für einige Dinge aus ... wie ich bin ein wenig neu zu ionischen/angular/typescript. Die 1500ms Verzögerung ist da, denn wenn es nicht der Code in 'this.geolocation.getCurrentPosition() ist, dann wird ((resp) => {' ausgeführt, bevor die Positionskoordinaten tatsächlich erhalten werden. Ich verwende 'this', um darauf Bezug zu nehmen zu den Klassen Methoden und Eigenschaften, sowie injizierte Module ('Konstruktor (xxx: XXXXXX)'). Ich habe einige dieser Dinge gelernt und ging sehr schnell zur gleichen Zeit, weil ich nicht viel Zeit dafür hatte. ..Ich hätte gerne mehr auf Best Practices geachtet. – ewizard

Antwort

2

Sie haben Codepfade, die speziell nicht beheben:

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

natürlich bekommen ... danke! – ewizard

0

Es ist sehr einfach in Deadlocks bekommen wie @ andy-gaskell wies darauf hin, wenn neue Versprechungen zu schaffen. Um das zu vermeiden, tust du besser eines davon; All dies kann eine unmögliche Fehler werfen oder 1. Rückkehr

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

den Kommentar mit Ihrem Code ersetzen und das Ende Ergebnis in die Variable Ergebnis platzieren. Wenn Ihr Code Asynchron-Code enthält, sollten Sie besser eine neue Funktion mit dem gleichen Muster machen und zurück, dass als Ergebnis, zum Beispiel: Ergebnis = [Versprechen Methode]

  • Die beängstigend ist „neue Promise“, falls vorhanden Code wird nicht aufgelöst oder abgelehnt wird in einem "Dead-Lock" enden, deshalb ist es wichtig zu versuchen/fangen.
  • Wenn Sie Promise.resolve() verwenden, fängt es alle Fehler in .then, aber keinen Code außerhalb. Dann müssen Sie Ausnahme abfangen und eine Promise.reject (new Error())
  • zurückgeben
  • Die sicherste ist Asynchron-Funktion, da jeder „werfen“ eine Promise.reject zurückkehren und „Rückkehr“ wird ein Promise.resolve

mit diesem Beispiel spielt um zurückzukehren, aber ich hatte auszukommen async/warten Sie ab, da dieses Snippet-Tool ES2016 nicht verarbeitet.

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)); 
 
*/

+0

vielen Dank, dass Sie darauf hingewiesen haben. Können Sie mir ein wenig mehr erklären, wie ich diese Methoden verwenden würde, um Deadlocks zu vermeiden? – ewizard

+0

hinzugefügt ein Beispiel und weitere Beschreibung für jeden Fall – Lostfields

Verwandte Themen