基于条件的Promise.all()解构赋值结果错位问题求助
解决Promise.all解构时因条件缺失导致变量错位的问题
你的问题核心在于:通过条件判断动态往promises数组中添加Promise时,缺失的条件会导致数组长度和预期的解构变量数量不匹配,最终解构后变量对应的数据错位。
按照限制条件,这里提供直接有效的修改方案:
// 为每个预期变量固定位置,条件不满足时用Promise.resolve(undefined)占位 const promises = [ false ? Promise.resolve("highlights from DB") : Promise.resolve(undefined), true ? Promise.resolve("featured video from DB") : Promise.resolve(undefined), true ? Promise.resolve("categories from DB") : Promise.resolve(undefined) ]; const [highLightVideo, featuredVideo, categories] = await Promise.all(promises); console.log("highLightVideo: ", highLightVideo); console.log("featuredVideo: ", featuredVideo); console.log("categories: ", categories); } main();``` ### 方案说明 - 不再动态`push`Promise,而是预先构建与解构变量数量一致的数组 - 每个数组位置对应一个解构变量,条件不满足时用`Promise.resolve(undefined)`填充该位置,确保数组索引和变量位置完全对应 - 执行`Promise.all`后,解构的变量会精准匹配对应位置的结果,不会出现错位或`undefined`位置错误的情况 运行修改后的代码,就能得到你预期的输出: ```highLightVideo: undefined featuredVideo: featured video from DB categories: categories from DB``` 内容的提问来源于stack exchange,提问作者Ashutosh
相关产品推荐
相关产品推荐

