【问题标题】:Javascript How to migrate promise.spread syntax to async/await with destructuringJavascript 如何通过解构将 promise.spread 语法迁移到 async/await
【发布时间】:2018-09-20 18:37:01
【问题描述】:

我正在清理一些sequelize 代码,findOrCreate 函数返回一个承诺,需要传播才能获得实际结果对象。

我想重写我的代码以改用await,并且考虑到 ES6 支持数组解构,我原本认为不是

User.findOrCreate({ where: { mcId }, defaults }).spread((user, created) => {
  // do stuff
})

我能做到

const [user, created] = await User.findOrCreate({ where: { mcId }, defaults })

可惜事实并非如此。

我收到错误(intermediate value) is not iterable

这样做有什么特别的技巧吗?或者我想要做的事情是不可能的?

【问题讨论】:

  • Note that .spread() implicitly does .all() but the ES6 destructuring syntax doesn't - 所以,也许是const [user, created] = await User.findOrCreate({ where: { mcId }, defaults }).all();
  • 奇怪的是,如果我这样做,我会收到此错误 SequelizeDatabaseError: relation "Users" does not exist — 但使用旧的 spread 表示法我不会收到此类错误。
  • 除非您使用 2014 年之前的 sequelize 版本,否则 findOrCreate 应该返回一个数组并假设它返回一个承诺,那么传播应该可以正常工作。结果是什么:findOrCreate(...).then(result=>console.log(result))
  • 我最终没有使用findOrCreate。如果我有时间,稍后会回来。

标签: javascript promise async-await spread-syntax


【解决方案1】:

我正在使用 Sequelize v4.37.10,这对我有用 -

 const [address, created] = await models.Address.findOrCreate({ where: { pid: 123}, defaults});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多