将Promise.all保存到两个变量中

3
我有这段代码,想将Promise.all的结果保存到两个变量中。问题是当(this.data = data)时,它会变成undefined。
    const {data,recents} : any = await Promise.all([
      this.$store.dispatch('algo', input),
      this.$store.dispatch('algo', input)
    ])
    this.data = data
    this.recents = recents

3
我会假定Promise.all会解析一个数组。因此使用对象解构将不起作用。尝试使用数组解构代替? - evolutionxbox
“存储结果”是什么意思?Promise.all并不会产生除等待数组中所有 Promise 都已解决之外的任何结果。请参见 单一 Promise - Mike 'Pomax' Kamermans
2个回答

5

Promise.all 返回一个 Promise,它将会以一个由各个 promise 结果组成的 数组 来完成。你不能从中解构任意命名的对象属性 - 而需要使用数组解构!

const [data, recents] = await Promise.all([
//    ^             ^
    this.$store.dispatch('algo', input),
    this.$store.dispatch('algo', input)
])
this.data = data
this.recents = recents

或者不使用临时变量的更简洁写法:

;[this.data, this.recents] = await Promise.all([
    this.$store.dispatch('algo', input),
    this.$store.dispatch('algo', input)
])

2
我认为Promise.all会返回一个数组,因此使用对象解构将不起作用。
尝试改用数组解构:

(async() => {

  const [
    data,
    recents
  ] = await Promise.all([
    Promise.resolve('data'),
    Promise.resolve('recents')
  ]);

  console.log(
    data,
    recents
  );

})();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接