TypeScript 结合多个 Promise 等待

TypeScript combine multiple Promises await

我基本上有一段代码,其中我有一个变量,用于合并多个 promise 等待并将它们连接到一个对象中

const traversals = (await traverseSchemas({filename:"my-validation-schema.json"}).concat([
      _.zipObject(
        ["id-1", "id-2"],
        [
          await loadSchema({
            filename: "schema-1.json"
          }),
          await loadSchema({
            filename: "schema-2.json"
          }),
        ]
      ),
    ]);  

traverseSchemasreturns一个数组对象[{"key1":{object}}, {"key2": {object}}]

我正在探索是否可以在 traversals 级别应用 await 来获取所有承诺的已实现数据,或者是否有任何更好的方法来重构代码。

因为没有承诺依赖于另一个承诺的结果,所以您可以使用 Promise.all 同时(并行)执行所有这些承诺。这仅使用单个 await,而 return ... 是一个纯同步表达式,结合了等待的值 -

async function traversals() {
  const [validation, schema1, schema2] = await Promise.all([
    traverseSchemas({filename:"my-validation-schema.json"}),
    loadSchema({filename: "schema-1.json"}),
    loadSchema({filename: "schema-2.json"}),
  ])

  return [
    ...validation,
    _.zipObject(["id-1", "id-2"], [schema1, schema2])
  ]
}

如果您有权访问 top-level await 或者这已经是另一个 async 函数的一部分,您可以定义 const traversals = ... 而不是使用 return -

const [validation, schema1, schema2] = await Promise.all([
  traverseSchemas({filename:"my-validation-schema.json"}),
  loadSchema({filename: "schema-1.json"}),
  loadSchema({filename: "schema-2.json"}),
])

const traversals = [
  ...validation,
  _.zipObject(["id-1", "id-2"], [schema1, schema2])
]

有很多选择。

通常明码更容易理解。所以我会选择这样的东西:

const validationSchemas = await traverseSchemas({ filename:"my-validation-schema.json" })
const schema1 = { "id-1": await loadSchema({ filename: "schema1-json" });
const schema2 = { "id-2": await loadSchema({ filename: "schema2-json" });

const traversals = [ ...fetchedSchemas, schema1, schema2 ];

如果你想并行等待,你可以先准备它们,然后通过Promise.all请求,然后连接在一起:

const tasks = [
    traverseSchemas({ filename:"my-validation-schema.json" }),
    loadSchema({ filename: "schema1-json" }),
    loadSchema({ filename: "schema2-json" })
];

const [validationSchemas, schema1Value, schema2Value] = await Promise.all(tasks);

const traversals = [
    ...validationSchemas,
    { 'id-1': schema1Value },
    { 'id-2': schema2Value }
];