[英]Is there a log function that will add the log invocation to the control-flow in Protractor?
[英]Control-Flow with NodeJS and Sequelize
我有以下功能:
function retrieveNotifications(promotions) {
promotions.forEach( function(promotion) {
//find all notification groups that have to be notified
db
.Notification
.findAll()
.then(function (notifications) {
//some code that adds notifications to an object
});
});
};
如何重新构建它以等待所有通知都添加到对象。 我不能使用.then
因为forEach
会被多次调用
我建议使用异步库: https : //github.com/caolan/async
基本上它会是这样的:
async.parallel([
// tasks..
],
function () {
// this is the final callback
})
您可以使用内置于Sequelize / Bluebird中的.spread():
让你的forEach构建一个db.Notification.findAll()
数组并返回它。 然后在结果上调用.spread。 如果您不知道返回的数组的长度,则可以在成功回调中使用arguments
对象。
现在.spread()将一直等到数组中的每个元素都返回并传递一个包含所有Notification行的数组。
您正在寻找Bluebirds集合函数 ,特别是map
, each
或prop
。 它们将允许您使用异步回调迭代promotions
数组,并且您将获得一个仅在所有这些回复完成后自动解析的回复。
在你的情况下,它看起来像这样:
function retrieveNotifications(promotions) {
return Promise.map(promotions, function(promotion) {
// find all notification groups that have to be notified
return db.Notification.findAll(… promotion …);
}).then(function(results) {
// results is an array of all the results, for each notification group
var obj = {};
for (var i=0; i<results.length; i++)
//some code that adds notifications to the object
return obj;
});
// returns a promise for that object to which the notifications were added
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.