javascript - 在 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 结果动态绑定到变量?
解决方案
选项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
推荐阅读
- arrays - 将值推入多维数组时出现 TSLint 接口错误
- javascript - 运行 .js 文件的 CronJob 不会将控制台输出到 .txt 或 .log 文件
- c# - 数据网格视图上未显示任何数据
- python - 想要使用经过预训练的 ResNet50 但出现错误“ValueError: Shapes (None, None) and (None, 7, 7, 3) are incompatible”
- css - 如何覆盖 CSS 默认主题 CSS WordPress
- firebase - 检索存储在 Firebase 存储中的图像
- json - 如何在codeigniter中的php中发送json对象值?
- python - scikit-learn 中的 StratifiedKFold 与 KFold
- flutter - 无法加载资产:/data/user/0/com.example.app/app_flutter/localization/en-IN.json 直到热重新加载
- fortran - Fortran 中释放可分配数组的问题