我想在 map 内的每个循环内进行查询,然后一旦完成循环和查询就执行其他操作:
Promise.map(results, function (item, index) {
return Clubs.findAsync({name: name})
.then(function (err, info) {
if (err) {console.info(err); return err};
console.info(info);
return info;
})
.done(function (info) {
return info;
});
}).done(function (data) {
console.info('done');
req.flash('success', 'Results Updated');
res.redirect('/admin/games/'+selectedLeague);
});
在此,done
将在 info
被控制台之前进行控制台。这意味着我无法对数据做任何事情。
最佳答案
来自bluebird.done :
.done([Function fulfilledHandler] [, Function rejectedHandler ]) -> void
Like .then(), but any unhandled rejection that ends up here will be thrown as an error. Note that generally Bluebird is smart enough to figure out unhandled rejections on its own so .done is rarely required. As explained in the error management section, using .done is more of a coding style choice with Bluebird, and is used to explicitly mark the end of a promise chain.
因此,在您的 Promise.map
中,它只获得一个 undefined
数组或其他内容,但不是 Promise
,因此 map 是拿到 map 后就解决了。使用 .then
返回一个 Promise
。
Promise.map(results, function (item, index) {
return Clubs.findAsync({name: name})
.then(function (err, info) {
if (err) {console.info(err); return err};
console.info(info);
return info;
})
// vvvv use `.then` here, not `.done`, done returns nothing, not promise.
.then(function (info) {
return info;
});
}).done(function (data) {
console.info('done');
req.flash('success', 'Results Updated');
res.redirect('/admin/games/'+selectedLeague);
});
关于javascript - 在循环使用 Mongoose 查询时有希望 - Node Bluebird,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31853690/