首页 > 解决方案 > 在 Promise 的动态数组的情况下,如何知道 Promise.all 返回哪个变量

问题描述

const promisesArray = [];

if (condition) {
  const promiseA = fetchA();
  promisesArray.push(promiseA)

}
if (condition) {
  const promiseB = fetchB();
  promisesArray.push(promiseB)

}
if (condition) {
  const promiseC = fetchC();
  promisesArray.push(promiseC)
}

// Could have 1, 2 or 3 elements
const [???] = await Promise.all(promisesArray);

使用这种模式,我如何将 promise 结果动态绑定到变量?

标签: javascriptpromiseasync-await

解决方案


选项1:

我想我会在一个对象中标记每个结果,然后当您遍历结果时,您可以知道哪些存在,哪些不存在。您不能真正直接从Promise.all()结果中使用命名解构,因为您不知道哪些结果在Promise.all()数组中,哪些不在。因此,您似乎需要迭代结果并动态适应那里的结果。我的猜测是,有一种更好的整体方法来编码这个特殊情况,但你必须向我们展示你的真实代码,以便我们提供基于此的更好方法。无论如何,这是一个通用的迭代解决方案:

const promisesArray = [];

if (condition) {
  const promiseA = fetchA().then(result => ({a: result}));
  promisesArray.push(promiseA)

}
if (condition) {
  const promiseB = fetchB().then(result => ({b: result}));
  promisesArray.push(promiseB)

}
if (condition) {
  const promiseC = fetchC().then(result => ({c: result}));
  promisesArray.push(promiseC)
}

// Could have 1, 2 or 3 elements
let results = await Promise.all(promisesArray);
let combined = Object.assign({}, ...results);
// now you have a single object that has each results, tagged with a key that
// represents which function it came from

选项#2:

您也可以为每个结果推送一个占位符,即使它没有异步操作,然后您将保持在数组中的位置并可以直接解构。

const promisesArray = [];

if (condition) {
  const promiseA = fetchA();
  promisesArray.push(promiseA)
} else {
  promisesArray.push(null);
}

if (condition) {
  const promiseB = fetchB();
  promisesArray.push(promiseB)
} else {
  promisesArray.push(null);
}

if (condition) {
  const promiseC = fetchC();
  promisesArray.push(promiseC)
} else {
  promisesArray.push(null);
}

// Could have 1, 2 or 3 elements
let [aResult, bResult, cResult] = await Promise.all(promisesArray);
// results that were skipped will be null

推荐阅读