【问题标题】:Destructuring from Promise.all into object从 Promise.all 解构到对象
【发布时间】:2021-07-17 07:09:26
【问题描述】:

我发现自己现在写了很多类似的代码

const arr = await Promise.all([getName(), getLocation(), getDetails()])
const obj = {
    name: arr[0],
    location: arr[1],
    details: arr[2]
}
// send obj to somewhere else

这很丑陋。我希望有类似的东西

const obj = {}
[obj.name, obj.location, obj.details] = await Promise.all([getName(), getLocation(), getDetails()])

但这失败了。有没有一种优雅的方式来进行这样的解构?

【问题讨论】:

  • 据我了解,这应该可以工作。你能澄清一下“这失败了”是什么意思吗?是否抛出错误?如果是,请分享,如果不分享结果是什么,以及它与您的预期相比如何。

标签: javascript node.js promise destructuring


【解决方案1】:

使用destructuring assignment:

const [name, location, details] = await Promise.all([getName(), getLocation(), getDetails()]);

const obj = { name, location, details };

【讨论】:

    【解决方案2】:

    确实工作。您只需在此处添加分号即可。

    (async () => {
      const obj = {}; // <------------------------------
      [obj.first, obj.second, obj.third] = await Promise.all([1,2,3])
      console.log(obj)
    })()

    【讨论】:

      【解决方案3】:
      await Promise.all([getName(), getLocation(), getDetails()])
          .then(([name, location, details]) => ({ name, location, details }));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-17
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 2021-01-17
        相关资源
        最近更新 更多