promise all convert the result into an object

cuc*_*uru 4 promise angular

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]
      })
  ) 
}
Run Code Online (Sandbox Code Playgroud)

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?

Dan*_*pel 9

您实际上可以此处使用es6 中析构。由于您Promise.all(...)将解决与在它三个项目的数组,你可以[first, second, third]作为参数传递给箭头功能和JavaScript将采摘的项目出自己的位置的阵列中,并将它们设为变量与相应的名称(即firstsecond,而third在这种情况下)。

此外,如果您保持变量名称与对象的属性名称相同,您可以使用下面的简写语法来创建对象。

resolve(route: ActivatedRouteSnapshot): Promise<any> {
    return Promise.all([
        this.service1.getAll(),
        this.service2.getAll(),
        this.service3.getAll()
    ]).then(([first, second, third]) => ({ first, second, third }));
}
Run Code Online (Sandbox Code Playgroud)

作为参考,TypeScript 将 中的代码.then(...)转换为以下 es5 JavaScript:

.then(function (_a) {
    var first = _a[0], second = _a[1], third = _a[2];
    return ({ first: first, second: second, third: third });
})
Run Code Online (Sandbox Code Playgroud)


sid*_*mor 6

你可以用ES6做到这一点:

const [x,y,z] = ['E','S','6'];
// x = 'E'
// y = 's'
// z = '6'
Run Code Online (Sandbox Code Playgroud)

所以你可以使用相同的Promise.all

const [first, second, third] = await Promise.all([
  this.service1.getAll(),
  this.service2.getAll(),
  this.service3.getAll()
]);
Run Code Online (Sandbox Code Playgroud)


Sac*_*hah 0

试试这个方法

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

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

我希望这可以帮助你......:)

对象中的数据