Javascript 如何知道Promise.all返回的是哪个变量,以防Promise的动态数组

Javascript 如何知道Promise.all返回的是哪个变量,以防Promise的动态数组,javascript,promise,async-await,Javascript,Promise,Async Await,使用此模式,如何将promise结果动态绑定到变量?选项#1: 我想我应该在一个对象中标记每个结果,然后当您遍历结果时,您可以知道哪些结果存在,哪些不存在。您不能直接从Promise.all()结果中使用命名的分解结构,因为您不知道哪些结果在Promise.all()数组中,哪些不在数组中。因此,您似乎需要迭代结果,并动态调整结果。我的猜测是,有一种更好的总体方法来编写这个特定案例,但您必须向我们展示您的真实代码,以便我们提供一种基于此的更好方法。无论如何,这里有一个通用的迭代解决方案: con

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

选项#1:

我想我应该在一个对象中标记每个结果,然后当您遍历结果时,您可以知道哪些结果存在,哪些不存在。您不能直接从
Promise.all()
结果中使用命名的分解结构,因为您不知道哪些结果在
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);
选项2:

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

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

这回答了你的问题吗?这不是最简单的方法,因为在实践中,我的函数有参数,但当我的条件为falsy时,传递null而不是承诺就完成了!谢谢
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