I want to get data from DB based on the boolean flag.
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();
Above code output:
highLightVideo: featured video from DB
featuredVideo: categories from DB
categories: undefined
Output I need:
highLightVideo: undefined
featuredVideo: featured video from DB
categories: categories from DB
Note: (Solution that won’t work for me because of project structure)
- I cannot use
.then()
flow. - I cannot return any custom value like this
promises.push(Promise.resolve({ msg: "highlights from DB", type: 'HIGHLIGHT' }));
2
Answers
Just push a resolved promise of
undefined
for the things you don’t care about, so the length ofpromises
is always 3 and you can destructure it in a constant way:You can resolve any static value with
Promise.all()
. In this option empty values will be equalfalse
:If you want exact
undefined
: