【发布时间】:2017-11-02 10:40:45
【问题描述】:
我有一个异步函数,它调用其他异步函数,当它们都完成后,我将返回结果。
我不想使用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);
}
});
});
});
};
【问题讨论】:
-
您检查过
async模块吗?它将为您节省很多头疼 -
@borislemke
async.parallel似乎不接受第一个参数的承诺,我不想做任何奇怪的黑客攻击并将承诺转换为回调,我试图让代码变得更好尽可能
标签: javascript node.js asynchronous ecmascript-6 async-await