admin管理员组

文章数量:1330679

I'm cleaning up some sequelize code and the findOrCreate function returns a promise that requires spreading to get the actual result object.

I'd like to rewrite my code to use await instead and, given ES6 supports array destructuring I'd have thought that instead of

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

I'd just be able to do

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

but alas that's not the case.

I get the error (intermediate value) is not iterable

Is there any special trick to doing this or is what I am trying to do just not possible?

I'm cleaning up some sequelize code and the findOrCreate function returns a promise that requires spreading to get the actual result object.

I'd like to rewrite my code to use await instead and, given ES6 supports array destructuring I'd have thought that instead of

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

I'd just be able to do

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

but alas that's not the case.

I get the error (intermediate value) is not iterable

Is there any special trick to doing this or is what I am trying to do just not possible?

Share edited Sep 7, 2018 at 0:15 Patrick Roberts 52k10 gold badges117 silver badges163 bronze badges asked Apr 11, 2018 at 2:26 Dave SagDave Sag 13.5k14 gold badges91 silver badges139 bronze badges 4
  • 2 Note that .spread() implicitly does .all() but the ES6 destructuring syntax doesn't - so, perhaps const [user, created] = await User.findOrCreate({ where: { mcId }, defaults }).all(); – Jaromanda X Commented Apr 11, 2018 at 2:34
  • weirdly if I do that I get this error SequelizeDatabaseError: relation "Users" does not exist — but with the old spread notation I get no such error. – Dave Sag Commented Apr 11, 2018 at 2:54
  • Unless you use a pre 2014 version of sequelize the findOrCreate should return an array and assuming it returns a promise then the spread should just work. What is result in: findOrCreate(...).then(result=>console.log(result)) – HMR Commented Apr 11, 2018 at 3:43
  • I ended up just not using findOrCreate. Will e back to this later if I get time. – Dave Sag Commented Apr 23, 2018 at 2:32
Add a ment  | 

1 Answer 1

Reset to default 7

I'm using Sequelize v4.37.10 and this worked for me -

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

本文标签: Javascript How to migrate promisespread syntax to asyncawait with destructuringStack Overflow