promise all convert the result into an object

Viewed 7589

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?

3 Answers

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()
]);

Try this way

resolve(route: ActivatedRouteSnapshot): Promise<any> {

 return Promise.all([
this.service1.getAll(),
this.service2.getAll(),
this.service3.getAll()]
  .map((result) => {
    this.allData = Object.assign({},result)
  })
 ) 
} 

I hope this may help you... :)

Data in object

Related