Promises in Sequelize: how to get results from eac

2020-07-03 07:31发布

问题:

In Sequelize >=1.7 we can use promises

Can you explain for me how can i get values from each user in this code:

var User = sequelize.define("user", {
  username: Sequelize.STRING
})


User
  .sync({ force: true })
  .then(function() { return User.create({ username: 'John' }) })
  .then(function(john) { return User.create({ username: 'Jane' }) })
  .then(function(jane) { return User.create({ username: 'Pete' }) })
  .then(function(pete) {
    console.log("we just created 3 users :)")
    console.log("this is pete:")
    console.log(pete.values)

    // what i want:
    console.log("this is jane:")
    console.log(jane.values)

    console.log("this is john:")
    console.log(john.values)
  })

UPD

All values need for set associations with other Model. Actually i need some like this code:

User.hasMany(Group)
Group.hasMany(User)

User
  .sync({ force: true })
  .then(function() { return User.create({ username: 'John' }) })
  .then(function(john) { return User.create({ username: 'Jane' }) })
  .then(function(jane) { return User.create({ username: 'Pete' }) })
  .then(function(pete) { return Group.findOrCreate({id: 1}) })
  .then(function(group) {return group.setUsers([john, jane, pete])})
  .then(function(result) { console.log(result)})
})

回答1:

The Bluebird way are the collection helper functions.

If you want to create them in parallel, use map:

User.sync({ force: true })
  .then(function() {
    return Promise.map( ['John', 'Jane', 'Pete'], function(name) {
      return User.create({ username: name });
    })
  }).spread(function(john, jane, pete) {
    console.log("we just created 3 users :)")
    console.log("this is john:")
    console.log(john.values)
    console.log("this is jane:")
    console.log(jane.values)
    console.log("this is pete:")
    console.log(pete.values)
  })

If you need to create them consecutively, just change it to mapSeries (3.0+).

If the array doesn't need to be dynamic, and you simply want to pass a shared value through the promise chain like in your example, have a look at How do I access previous promise results in a .then() chain?.



回答2:

Using no additional libraries (and if you need to maintain the order of creates), you can do this by simply creating variable(s) in the enclosing scope which hold the values:

var created = {};
User
  .sync({ force: true })
  .then(function() { return User.create({ username: 'John' }) })
  .then(function(john) { created.john = john; return User.create({ username: 'Jane' }) })
  .then(function(jane) { created.jane = jane; return User.create({ username: 'Pete' }) })
  .then(function(pete) {
    created.pete = pete;

    console.log("we just created 3 users :)")
    console.log("this is pete:")
    console.log(created.pete.values)

    // what i want:
    console.log("this is jane:")
    console.log(created.jane.values)

    console.log("this is john:")
    console.log(created.john.values)
  })

In general though, I would recommend that you lean towards @Bergi's answer which creates a list of Promises and waits for all of the promises to complete.

Edit based on question update:

Using your updated code block and building on @Bergi's suggestion of Promise.map, you can avoid using variables in a higher scope with something like the following:

User.hasMany(Group)
Group.hasMany(User)

User
  .sync({ force: true })
  .then(function() {
    var users = Promise.map( ['John', 'Jane', 'Pete'], function(name) {
      return User.create({ username: name });
    });
    var group = Group.findOrCreate({id: 1});
    return Promise.all([group, users]);
  })
  .spread(function(group, users) {return group.setUsers(users)})
  .then(function(result) { console.log(result)})
})


回答3:

Try this...

User
    .sync({ force: true })
    .then(function () {
        return User.create({ username: 'John' });
    })
    .then(function (john) {
        console.log("this is john:");
        console.log(john.values);
        return User.create({ username: 'Jane' });
    })
    .then(function (jane) {
        console.log("this is jane:");
        console.log(jane.values);
        return User.create({ username: 'Pete' });
    })
    .then(function (pete) {
        console.log("we just created 3 users :)");
        console.log("this is pete:");
        console.log(pete.values);
    });