[英]Chaining mongoose promises in a for loop
I have an api that creates a new document in mongodb using this function: 我有一个使用此功能在mongodb中创建新文档的api:
export function create(req, res) {
return Track.create(req.body)
.then(respondWithResult(res, 201))
.catch(handleError(res));
}
This just adds a new document, I would like to extend this and after the document was added I would like to add some more documents into another collection with the information from the response, something like this: 这只是添加了一个新文档,我想扩展它,添加文档后,我想使用响应中的信息将更多文档添加到另一个集合中,如下所示:
export function create2(info) {
var trackId = info._id;
var users = info.users;
var basic = {
trackId : trackId
};
for (let user of users) {
basic.username = user.username;
Location.create(basic);
}
}
I would like to call the create2 function on a .then of the promise from the first create function something like this: 我想在.then调用第一个create函数的promise上的create2函数,如下所示:
export function create(req, res) {
return Track.create(req.body)
.then(create2)
.then(respondWithResult(res, 201))
.catch(handleError(res));
}
The problem is that create2 does not return a promise and I don't really know how to chain the promises returned by Location.create in create2? 问题是create2不会返回承诺,而且我真的不知道如何在create2中链接Location.create返回的承诺?
The way to make create2
return a promise is with Promise.all() , which is fulfilled when the array of promises passed to it are all fulfilled. 使create2
返回承诺的方法是使用Promise.all() ,当传递给它的所有承诺数组都满足时,该方法即告实现。 Something like this... 像这样
var _ = require('underscore'); // optional but useful for a better loop with '.map'
export function create2(info) {
var trackId = info._id;
var users = info.users;
var basic = {
trackId : trackId
};
var promises = _.map(users, function(user) {
basic.username = user.username;
return Location.create(basic);
});
return Promise.all(promises);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.