I'm using promise.all in my resolver, it works, but now, I don't want an array of promises but an object, but I can't find how to do it.
This is my try:
resolve(route: ActivatedRouteSnapshot): Promise<any> {
return Promise.all([
this.service1.getAll(),
this.service2.getAll(),
this.service3.getAll()]
.map((result) => {
first: result[0],
second: result[1],
third: result[2]
})
)
}
As you can see I want to convert the array into an object with key - value
how can I map the result to get an object instead the array?
The new Promise() constructor returns a promise object. As the executor function needs to handle async operations, the returned promise object should be capable of informing when the execution has been started, completed (resolved) or retuned with error (rejected).
all() The Promise. all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will fulfill when all of the input's promises have fulfilled, or if the input iterable contains no promises.
Promise. all is all or nothing. It resolves once all promises in the array resolve, or reject as soon as one of them rejects. In other words, it either resolves with an array of all resolved values, or rejects with a single error.
You can actually make use of destructring in es6 here. Since your Promise.all(...)
will resolve to an array with three items in it, you can have [first, second, third]
as the parameter to the arrow function and JavaScript will pluck the items out of their place in the array and set them to variables with the corresponding names (ie. first
, second
, and third
in this case).
Additionally, if you keep the variable name the same as the property name for the object you can use the short hand syntax below for creating the object.
resolve(route: ActivatedRouteSnapshot): Promise<any> {
return Promise.all([
this.service1.getAll(),
this.service2.getAll(),
this.service3.getAll()
]).then(([first, second, third]) => ({ first, second, third }));
}
For reference, TypeScript transpiles the code in the .then(...)
to the following es5 JavaScript:
.then(function (_a) {
var first = _a[0], second = _a[1], third = _a[2];
return ({ first: first, second: second, third: third });
})
You can do this with ES6:
const [x,y,z] = ['E','S','6'];
// x = 'E'
// y = 's'
// z = '6'
So you can use the same with Promise.all
const [first, second, third] = await Promise.all([
this.service1.getAll(),
this.service2.getAll(),
this.service3.getAll()
]);
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