基于动态或条件的 Promise.all() 和析构

问题描述 投票:0回答:1

我想根据布尔标志从数据库获取数据。

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' }));
javascript promise destructuring
1个回答
1
投票

只需为你不关心的事情推送

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));

© www.soinside.com 2019 - 2024. All rights reserved.