简体   繁体   English

等待并在 object 中一起返回所有已解析的 promise 值

[英]Await and return all resolved promise values together within an object

I have an object we'll call pages where the value for each key ( typeOne , typeTwo , etc...) is an array of objects - and a key in that object called formData is a pending Promise.我有一个 object 我们将调用pages ,其中每个键( typeOnetypeTwo等...)的值是一个对象数组 - 并且 object 中的一个名为formData的键是待处理的 ZA5A3F0F287A4478982AAC520CFFE。 I'd like to essentially update the pages object such that each formData key is the promise's resolved value.我想从根本上更新pages object 以便每个formData键都是承诺的解析值。

I have successfully been able to do so by essentially mapping through each of the values in pages - however, this is slow because seems to await and resolve each type* 's array set before moving to the next set, if that makes any sense.通过基本上映射pages中的每个值,我已经成功地做到了这一点 - 但是,这很慢,因为似乎在移动到下一个集合之前等待并解析每个type*的数组集,如果这有任何意义的话。

(async () => {
  let pages = {
    typeOne: [
      {
        formData: Promise<pending>
      },
      ...
    ],
    ...
  }
  ...
  for (type of _.keys(pages)) {
    pages[type] = await Promise.all(pages[type].map(async page => {
      page.formData = await page.formData;
      return page;
    })); 
  }
  ...
  // do stuff with pages
})()

Is there clean way to write this such that it awaits all Promises at once, then replaces the promises with the resolved values?是否有干净的方法来编写它,以便它立即等待所有 Promise,然后用已解决的值替换 Promise?

You need two Promise.all s;你需要两个Promise.all one to iterate over the keys, and another nested one to iterate over each page:一个迭代键,另一个嵌套一个迭代每个页面:

  const resolvedPages = {};
  await Promise.all(Object.entries(pages).map(([key, typeArr]) =>
    Promise.all(typeArr.map(
        // Wait for each individual Promise to resolve, then map to a new object
        ({ formData }) => formData.then(({ resolveValue }) => ({ formData: resolveValue }))
      )
      .then((resolvedArrOfObjs) => {
        resolvedPages[key] = resolvedArr;
      })
    )
  ))

No need for an iteration library.不需要迭代库。

Make sure not to implicitly create global variables, like with for (type of - that'll pollute the global scope or throw errors in strict mode.确保不要隐式创建全局变量,例如for (type of - 这会污染全局 scope 或在严格模式下抛出错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM