如何访问 async.parallel 的结果?

How to access results from async.parallel?

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

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

我仍在熟悉 async 和 promises,不确定如何实际访问这两个查询应返回的文档。任何帮助将不胜感激!

我当前的功能:

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);

    });
}

根据文档,exec() returns 一个承诺,如果您想使用回调,您可以将其作为参数传递给 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);
    });
}