我可能会把我目前处于同步状态的东西搞砸了,现在调试半天后很乐意接受任何帮助。
任务是异步更新数据库中的一堆实体。它是:
[{entity: 'Foo || Bar', id: foo.id || bar.id}]
形式的对象数组我目前拥有以下内容(使用Bluebird Promise.map):
exports.updateFooAndBars = function (req, res) {
var arrayOfFoos = req.body;
var projectId = req.params.projectId;
var result = [];
Promise.map(arrayOfFoos, function(foo, index){
var fooId = foo.id;
fooLib.update(foo, fooId)
.then(function (updatedFoo){
return barLib.update(foo, projectId);
});
})
.then(function(result) {
// handles PUT responses
updated(res, result);
})
.catch(function(err) {
.....
)};
这当然不起作用,因为最后一个.then-block在其他完成之前被调用。
但我无法找到在每次更新完成后我可以在何处以及如何准确地处理对客户端的响应?我在Promise.map(arrayOfFoos, function(foo, index)
中得到的索引在处理过程中完全搞乱了,当索引等于arrayOfFoos.length时,我似乎无法依赖它来发送响应。
并且由于可能会有相当多的实体在此过程中进行更新,因此我不希望这样同步,因为我可以避免在此过程中不阻止后端。
先感谢您!
最好的祝福,
Vegaa
你没有回到fooLib.update()
创建的Promise链。你的Promise.map()
正在遍历数组中的所有项目,调用回调并立即继续.then()
上的Promise.map()
,而不是等待从每个fooLib.update()
调用创建的所有Promise链。
使用Promises时,如果创建了任何内部Promise,则需要返回每个Promise,以确保所有异步工作都完全等待Promise链,如果这是您的代码所需要的。
Promise.map(arrayOfFoos, function(foo, index){
var fooId = foo.id;
return fooLib.update(foo, fooId)
.then(function (updatedFoo){
return barLib.update(foo, projectId);
});
})