我有一个异步函数,它调用其他异步函数,当它们全部完成时,我将返回结果。
我不想使用 Promise.all
,因为如果这些函数中的任何一个失败,我只是不会将它们添加到我的结果中。
ATM 我的代码如下所示。它可以工作,但我不喜欢 new Promise
,我想以 ES6 异步方式完成它,所以 callAll 函数应该看起来像 const callAll = async (query) => {
const callAll = (query) => {
return new Promise((resolve, reject) => {
const results = [];
const jobs = [
{
promise: someModuleFirst.search(query),
done: false
},
{
promise: someModuleSecond.search(query),
done: false
},
{
promise: someModuleThird.search(query),
done: false
}
];
const areAllDone = () => {
if(!jobs.filter((job) => !job.done).length) {
return true;
}
};
jobs.forEach((job) => {
job.promise.then((result) => {
job.done = true;
results.push(result);
if(areAllDone()) {
resolve(results);
}
}).catch((error) => {
job.done = true;
if(areAllDone()) {
resolve(results);
}
});
});
});
};
最佳答案
您可能可以将代码简化为以下内容。您可以从 catch
处理程序返回 false,然后过滤掉数据,这些数据不会传递到结果集中。
const callAll = async (query) => {
const modules = [someModuleFirst, someModuleSecond, someModuleThird];
const jobs = modules.map((module) => module.search(query).catch(() => false);
const results = await Promise.all(jobs);
return results.filter(Boolean);
};
关于javascript - 当有大量回调时,如何在异步函数中正确返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44304870/