I am creating an array, after it is created that array is resolved as a Object. However as I need to sort tempArray based on a particular value after the resolve I need it as an array, not an Object. Also because after the sort I am displaying it using: *ngFor. Or is it better to somehow sort the Object instead of changing it back to an array?
The console.log of the returned Promise is displayed underneath.
var tempArray = []
return new Promise((resolve, reject) => {
let error = false;
var i = 0;
for (let key of arrayOfPosts) {
tempArray[i] = {
"_id": key._id,
"postPub": key.postPub,
"timePast": this.timePastPublix
}
i++
}
if (error) {
reject('error')
} else {
resolve(tempArray)
}
});
{_id: "5aba1af4c97ce42ea81893bc", postPub: "0.00", timePast: "1970-01-01T01:00:00+01:00"}
{_id: "5ac698172910d705ecd66378", postPendingPayoutPublic: "0.00", timePast: "1970-01-01T01:00:00+01:00"}
You can just return it as an array, no need for an Object:
var promise = new Promise((resolve, reject) => {
resolve([1,2,3,4,5]);
});
// reject example
var promise2 = new Promise((resolve, reject) => {
var array = [];
if(array.length == 0)
reject("error");
else
resolve(array);
});
promise.then(data => console.log(data));
promise2.then(data => console.log(data))
.catch(error => console.log(error));
Here is a stackblitz which uses the promise array return values in an *ngFor: https://stackblitz.com/edit/angular-vpkk1a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With