在使用 mongoose 查询循环时有希望 - Node Bluebird
Promising whilst looping through with mongoose queries - Node Bluebird
我想在地图中的每个循环内执行查询,然后在完成循环和查询后执行其他操作:
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
被安慰之前被安慰。这意味着我无法对数据执行任何操作。
.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
,所以在它得到地图后解析地图。使用.then
到return一个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);
});
我想在地图中的每个循环内执行查询,然后在完成循环和查询后执行其他操作:
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
被安慰之前被安慰。这意味着我无法对数据执行任何操作。
.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
,所以在它得到地图后解析地图。使用.then
到return一个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);
});