我有6个异步请求。如果其中之一给出错误,则返回404,其他请求也无法正常工作。我使用async.parallel
发出这些请求。当其中一个失败时,我正在尝试处理其他请求。但是我做不到。
这是我的代码:
async.parallel({
request1: async (callback) => {
const [err, result] = await to(this.$store.dispatch('myAction1', {
id: this.$route.params.id,
}));
callback(err, result);
},
request2: async (callback) => {
const [err, result] = await to(this.$store.dispatch('myAction2', {
params: {
id: this.$route.params.id,
page: this.page,
size: this.size,
},
}));
callback(err, result);
},
request3: async (callback) => {
const [err, result] = await to(this.$store.dispatch('myAction3', {
data: {
filters: this.inputs.filters,
projections: this.inputs.projections,
showTotalCount: this.inputs.showTotalCount,
},
params: {
page: this.page,
size: this.size,
},
}));
callback(err, result);
},
request4: async (callback) => {
const [err, result] = await to(this.$store.dispatch('myAction4'));
callback(err, result);
},
request5: async (callback) => {
const [err, result] = await to(this.$store.dispatch('myAction5', {
id: this.$route.params.id,
}));
callback(err, result);
},
request6: async (callback) => {
const [err, result] = await to(this.$store.dispatch('myAction6', {
params: {
id: this.$route.params.id,
},
}));
callback(err, result);
},
}, (err, results) => {
if (err) {
// Show error message when one of them fails
}
// doing something when all requests success and hide the page loader.
this.hidePageLoader();
});
如果这些请求之一返回404,我想将失败的请求作为null
传递给我的results
对象,或者返回其他结果而没有在results
中失败的请求,则此代码始终显示页面加载器宾语。我该怎么做
答案 0 :(得分:0)
为使其余任务即使其他任务失败也能继续处理,您需要将任务推入一个数组,其中每个任务都用async.reflect
包装,并将任务数组设置为async.parallel
。
例如:
async.parallel([
async.reflect((callback) => {
return callback(null, "one");
}),
async.reflect((callback) => {
return callback("error");
}),
// another tasks
], function(error, results) {
if(error)
return cb(error)
// results[0].value ->> "one"
// results[1].error ->> "error"
return cb(results)
})
来源:Async Documentation utils
>> reflect