gpt4 book ai didi

javascript - 如何访问 async.parallel 的结果?

转载 作者:行者123 更新时间:2023-12-02 13:51:53 25 4
gpt4 key购买 nike

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

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

我仍在熟悉异步和 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);

});
}

最佳答案

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

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

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

或者,仅使用 Promise

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

关于javascript - 如何访问 async.parallel 的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40965095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com