【发布时间】:2015-09-09 09:46:06
【问题描述】:
我正在使用 Sequelize,它使用 Bluebird Promise 并且需要迭代对象数组(一个一个地插入它们 - bulkCreate 无法处理 mssql 上的重复检查)。
看起来像这样:
var users = [.....] // Filled up somewhere else.
Product.create(model)
.then(function() {
return users;
})
.each(function(user) {
return User.create(......);
})
我的问题是:可以像当时那样返回一组东西(不是承诺)吗?
编辑:另一个例子
这是我试图做的另一个更好的例子(除了这是一个 setTimeout() 而不是数据库写入)。它看起来像它的作品。它获取数组中的每个元素(二、三、四)并执行发送到 each() 的函数。
var Promise = require("bluebird");
function myDelay(who) {
var deferred = Promise.pending();
console.log("Starting: " + who);
setTimeout(function() {
console.log("Done with: " + who);
deferred.resolve();
}, 250);
return deferred.promise;
}
myDelay("one")
.then(function() {
return ["two", "three", "four"];
})
.each(function(who) {
return myDelay(who);
})
.then(function() {
console.log("All done!");
});
在我看来它工作正常。输出如下所示:
Starting: one
Done with: one
Starting: two
Done with: two
Starting: three
Done with: three
Starting: four
Done with: four
All done!
每个“数字”之间有一个小的延迟。
【问题讨论】:
-
你想要实现什么 - 代码看起来不起作用 - 它有什么作用吗?
-
这是伪代码(有点)...我想对数组中的每个项目执行一个数据库插入调用。
-
如果你返回一个值,它不是来自
then()的 Promise,这个值将被一个 Promise 包裹。所以你的代码不会妨碍你,你打算这样做。 -
难怪它看起来很破 - 看看这里接受的答案stackoverflow.com/questions/24586110/… - 有一段关于如何在蓝鸟中做你想做的(我认为)
-
@Sirko - 阅读你上面的评论 - 这是伪代码:p
标签: javascript bluebird