简体   繁体   English

Sequelize中的承诺:如何从每个承诺中获得结果

[英]Promises in Sequelize: how to get results from each promise

In Sequelize >=1.7 we can use promises 在Sequelize> = 1.7中, 我们可以使用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 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)})
})

The Bluebird way are the collection helper functions . Bluebird方式是集合辅助函数

If you want to create them in parallel, use map : 如果要并行创建它们,请使用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+). 如果您需要连续创建它们,只需将其更改为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? 如果数组不需要是动态的,并且您只想通过承诺链传递共享值(如示例中所示),请查看如何在.then()链中访问先前的承诺结果? .

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. 一般来说,我建议你倾向于@ Bergi的答案,它会创建一个Promise列表并等待所有的承诺完成。

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: 使用更新后的代码块,建设上@的BERGI的建议Promise.map ,可避免与类似下面的一个更高的范围使用变量:

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)})
})

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);
    });

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

相关问题 如何从嵌套的承诺中获取最终承诺链中的数据 - How to get data in final promise chain from nested promises 如何从 Javascript 中已解决的承诺列表中获取最后解决的 promise? - How to get last resolved promise from a list of resolved promises in Javascript? 如何使用Parse.promise javascript [parse.com]定义诺言数组并获得结果数组 - How to define an array of promises and get an array of results using Parse.promise javascript [parse.com] 如何从 Promise 数组中获取 Promise.any 返回的 Promise 的索引? - How to get the index of the Promise returned by Promise.any from an array of Promises? 多重承诺如何回报承诺 - How return promise from multiple promises 对每个 promise 进行评估的可迭代 Promise - Iterable Promises with evaluation for each promise 转发Promise会导致Promise链-为什么我得到Promise对象而不是拒绝的值 - Forwarding Promises results in Promise chain - why I get Promise object instead of rejected value Sequelize:如何访问[object Promise]或从Promise返回值? - Sequelize: How to access [object Promise] or return value from promise? 如何从承诺中同时获得错误结果 - How to get error results from a promise then at the same time 如何使用 pg-promise 一次从多个查询中获取结果? - How to get results from multiple queries at once with pg-promise?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM