What is Promise.all() in Typescript?
The Promise.all() function accepts a collection of promises as input and returns an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected. It is useful for aggregating all the promises and retrieving the results at the same time. It is typically useful when you want to load all the data at once before starting the desired functionality.
Promise.all() will reject any of the input promises immediately.
Code:
promiseall.component.ts:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-promiseall',
templateUrl: './promiseall.component.html',
styleUrls: ['./promiseall.component.css']
})
export class PromiseallComponent implements OnInit {
approach1: any[] = [];
approach2: any[] = [];
ngOnInit(){
debugger
this.executePromiseApproach1();
this.executePromiseApproach2();
}
getCustomerData(customerId: Number) {
return new Promise<Number>((resolve, reject) => {
resolve(customerId);
});
}
executePromiseApproach1(){
let customDataPromises:Promise<any>[] = [];
customDataPromises.push(this.getCustomerData(1));
customDataPromises.push(this.getCustomerData(2));
customDataPromises.push(this.getCustomerData(3));
return Promise.all(customDataPromises).then((result: any[]) => {
console.log(result);
this.approach1 = result;
});
}
executePromiseApproach2(){
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 1000, 'sample');
});
const promise2 = Promise.resolve(1000);
const promise3 = 500;
Promise.all([promise1, promise2, promise3]).then((result) => {
console.log(result);
this.approach2 = result;
});
}
}
promiseall.component.html:
<p>
Promise.all() approach 1: {{approach1}}
</p>
<p>
Promise.all() approach 2: {{approach2}}
</p>
Result:
- Promise.all() approach 1: 1,2,3
- Promise.all() approach 2: sample,1000,500
Download the above example source code from Github - Download
Leave a comment