【问题标题】:Does Promise.each in Bluebird has some kind of all operations finished callback?Bluebird 中的 Promise.each 是否有某种所有操作完成的回调?
【发布时间】:2016-08-17 14:45:38
【问题描述】:

我正在使用 Bluebird 处理 Promise,但我很难知道所有迭代何时完成,因此我可以将结果提交回客户端。

到目前为止,这是我的代码:

 Student.find({ status: 'student' })
    .populate('student')
    .exec(function (err, students) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        }
        Promise.each(students, function (student) {
            // console.log(student.id);
            return WorksnapsTimeEntry.find({ "student": student.id })
                .then(function (doc) {
                    var totalMinutes = 0;
                    var totalAvgLevelActivity = 0;
                    var counter = 0;
                    _.forEach(doc, function (item) {
                        if (item.timeEntries.duration_in_minutes) {
                            totalMinutes = totalMinutes + parseFloat(item.timeEntries.duration_in_minutes[0]);
                        }

                        if (item.timeEntries.activity_level) {
                            totalAvgLevelActivity = totalAvgLevelActivity + parseFloat(item.timeEntries.activity_level[0]);
                            counter++;
                        }
                    });

                    var obj = {};
                    obj.studentId = student.id;
                    obj.firstName = student.firstName;
                    obj.lastName = student.lastName;
                    obj.municipality = student.municipality;
                    obj.totalMinutes = totalMinutes;
                    obj.totalAvgLevelActivity = totalAvgLevelActivity / counter;
                    arrayReports.push(obj);
                })
        });
    });
    setTimeout(function () {
        res.json(arrayReports);
        console.log('finished.');
    }, 5000);

从上面的代码可以看出,我设置了5秒的超时时间,直到上述所有操作完成,然后将结果发送给客户端。

我正在寻找一些简单且我的代码不会发生太大变化的东西。

有人对此有任何想法吗?

【问题讨论】:

  • 阅读我对您其他问题的回答:stackoverflow.com/questions/36819137/… 它部分回答了这个问题。 Promise 可以使用then() 链接。在您的情况下,使用 bluebird 的 each 是不必要的,而且会浪费性能(它会串行处理输入,而不是同时处理所有请求)。

标签: javascript node.js mongoose promise bluebird


【解决方案1】:

根据doc here,Promise.each 返回一个promise。

Promise.each(
    Iterable<any>|Promise<Iterable<any>> input,
    function(any item, int index, int length) iterator
) -> Promise

所以,我猜你可以这样做:

Promise.each(students, function (student) {
     ....
}).then(function(){
    //all done 
    res.json(arrayReports);
    console.log('finished.');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    相关资源
    最近更新 更多