首页 > 解决方案 > Mongoose eachAsync:承诺的执行顺序出乎意料

问题描述

我正在使用库 mongoose 5.4.20、request 2.88.0、q 1.5.1 和 deasync 0.1.14。

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

请求承诺:

    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() 中的承诺解决之前被调用,即在 'console.log('B')' 之前调用'console.log('B')'。日志('A')'。我原以为 .eachAsync() 将等到 promise 被解决,然后从集合中提取下一个文档,依此类推,只有在最后,当所有 promise 都解决时,最终的 .then() 是叫。

任何关于我做错了什么的建议将不胜感激。谢谢。

标签: node.jsasynchronousmongoose

解决方案


推荐阅读