猫鼬eachAsync:承诺的执行顺序意外

时间:2019-04-02 13:11:39

标签: node.js asynchronous mongoose

我正在使用库mongoose 5.4.20,请求2.88.0,q 1.5.1和deasync 0.1.14。

当使用.cursor()和.eachAsync()时,承诺不会按我期望的顺序解析。特别是,我向数据库发出请求,并且对于每个返回的文档,我会通过异步序列发出多个外部请求。示例代码如下:

请求承诺:

    function Request (options) {
        const result = Q.defer();
        request(options, function (error, response, body) {
            if (error) {
                result.reject(error);
            } else {
                result.resolve(body);
            }
        });
        return result.promise;
    }

异步系列承诺:

    function Series (entry) {    
        const result = Q.defer();
        const errors = [];
        //Iterate over some given array
        async.eachSeries(array, function (doc, cb) {
            //Make some async request
            return Request(doc)
            .then(function (body) {
                //do stuff with 'body' and 'entry'
            })
            .then(function () {
                //Move to the next doc in 'array'
                return cb(null);
            })
            .fail(function (err) {
                //Handle errors
                errors.push(err);
                //Move to the next doc in 'array'
                return cb(null);
            });
        }, function (err, results) {
            if (err) {
                errors.push(err);
            }
            if (errors.length !== 0) {
                result.reject(errors);
            } else {
                console.log('A');
                result.resolve();
            }
        });
        return result.promise;
    }

猫鼬:

    mongooseModel
    .find()
    .cursor()
    .eachAsync(entry => Series(entry))
    .then(function () {
        console.log('B');
    }, function (err) {
        console.log(err);
    });

让我感到困惑的是,.eachAsync()之后的.then()中的最终回调似乎在.eachAsync()中的promise解决之前被调用,即,在之前调用了'console.log('B')' 'console.log('A')'。我本来希望.eachAsync()会等到承诺被解决,然后再从集合中提取下一个文档,依此类推,直到最后,当所有承诺都被解决时,最终的.then()是叫。

任何关于我做错事情的建议将不胜感激。谢谢。

0 个答案:

没有答案