我想根据布尔标志从数据库获取数据。
async function main() {
let promises = [];
if (false) {
promises.push(Promise.resolve("highlights from DB"));
}
if (true) {
promises.push(Promise.resolve("featured video from DB"));
}
if (true) {
promises.push(Promise.resolve("categories from DB"));
}
const [highLightVideo, featuredVideo, categories] = await Promise.all(promises);
console.log("highLightVideo: ", highLightVideo);
console.log("featuredVideo: ", featuredVideo);
console.log("categories: ", categories);
}
main();
以上代码输出:
highLightVideo: featured video from DB
featuredVideo: categories from DB
categories: undefined
我需要的输出:
highLightVideo: undefined
featuredVideo: featured video from DB
categories: categories from DB
注意:(由于项目结构,该解决方案对我不起作用)
.then()
流程。promises.push(Promise.resolve({ msg: "highlights from DB", type: 'HIGHLIGHT' }));
只需为你不关心的事情推送
undefined
的已解决承诺,因此promises
的长度始终为3,你可以以恒定的方式解构它:
const undefinedPromise = Promise.resolve(undefined);
async function getThings(highlights, featured, categories) {
const promises = [];
if (highlights) {
promises.push(Promise.resolve("highlights from DB"));
} else {
promises.push(undefinedPromise);
}
if (featured) {
promises.push(Promise.resolve("featured video from DB"));
} else {
promises.push(undefinedPromise);
}
if (categories) {
promises.push(Promise.resolve("categories from DB"));
} else {
promises.push(undefinedPromise);
}
return Promise.all(promises);
}
console.log(await getThings(true, false, true));
console.log(await getThings(false, true, true));
console.log(await getThings(true, true, true));