如何从async.parallel访问结果?

时间:2016-12-04 23:43:24

标签: javascript asynchronous mongoose promise async.js

我正在尝试使用async.parallel执行两个Mongoose查询,然后对结果执行某些操作。但是,当我尝试以results[0]results[1]的形式访问这些结果时,它们将作为Promises返回:

Promise {
_c: [],
_a: undefined,
_s: 0,
_d: false,
_v: undefined,
_h: 0,
_n: false } ]

我仍然熟悉异步和承诺,并且不确定如何实际访问应该由两个查询返回的文档。任何帮助将不胜感激!

我目前的职能:

export const getItems = (req, res) => {
    const itemId = "57f59c5674746a6754df0d4b";
    const personId = "584483b631566f609ebcc833";

    const asyncTasks = [];

    asyncTasks.push(function(callback) {
        try {
            const result = Item.findOne({ _id: itemId }).exec();
            callback(null, result);
        } catch (error) {
            callback(error);
        }
    });

    asyncTasks.push(function(callback) {
        try {
            const result = User.findOne({ _id: personId }).exec();
            callback(null, result);
        } catch (error) {
            callback(error);
        }
    });

    async.parallel(asyncTasks, function(err, results) {
        if (err) {
            throw err;
        }

        const result1 = results[0];
        const result2 = results[1];
        console.log('result' + result1);

    });
}

1 个答案:

答案 0 :(得分:2)

根据文档,exec()返回一个promise,如果你想使用一个回调你将它作为参数传递给exec - 就像这样

asyncTasks.push(function(callback) {
    Item.findOne({ _id: itemId }).exec(callback);
});

asyncTasks.push(function(callback) {
    User.findOne({ _id: personId }).exec(callback);
});

或者,仅使用Promises

export const getItems = (req, res) => {
    const itemId = "57f59c5674746a6754df0d4b";
    const personId = "584483b631566f609ebcc833";

    const promises = [];

    promises.push(Item.findOne({ _id: itemId }).exec());
    promises.push(User.findOne({ _id: personId }).exec());

    Promise.all(promises)
    .then(function(results) {
        const result1 = results[0];
        const result2 = results[1];
        console.log('result' + result1);
    })
    .catch(function(err) {
        console.log(err);
    });
}