I'm currently attempting to utilize Promise.all
and map
in place of the forEach loop to make the task asynchronous. All promises within the Promise.all
array are executed and resolved. Here is the code snippet:
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';
}*/
}
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");
resolve();
}).catch(e => {
console.log(e.message + " caught this error");
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 output on the console displays:
[12:38:27] console.log: I AM IN THE GEOCODING ***&&*&*&*&*
[12:38:27] console.log: push to the array of results
... (repeated messages) ...
[12:38:29] console.log: push to the array of results
Despite the alternating messages suggesting success with all promises being resolved, the line
console.log(JSON.stringify(arr) + " :FOSIEJO:SFJ::EFIJSEFIJS:EFJS:IO THIS IODIOSJ:FDSIJ :DIS");
never appears in the console. As a result, the then
block of the results
from Promise.all
is not reached.