【问题标题】:How to access results from async.parallel?如何从 async.parallel 访问结果?
【发布时间】:2017-04-19 07:19:52
【问题描述】:

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

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

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

我目前的功能:

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

    });
}

【问题讨论】:

  • 你应该使用 either async.js promises,但不能同时使用。
  • @Bergi - 我打算补充一下,但实际上找不到任何(合理的)讨论为什么同时使用两者是一个坏主意 - 我同意这是一个坏主意,我不能证明原因:p
  • @JaromandaX 我想我在我的几个答案中讨论过,但也找不到好的链接。要点基本上是,当您将 nodebacks 与 Promise 混合使用时,进行正确的错误处理更容易出错,并且您基本上丧失了 Promise 相对于回调的所有优势。

标签: javascript asynchronous mongoose promise async.js


【解决方案1】:

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

【讨论】:

  • 我很想知道您选择了哪个答案,因为我什至不确定第一个答案是否 100% 正确!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-23
相关资源
最近更新 更多