我对Promise的使用有点困惑。 请参阅以下示例:
Q1。如何停止连锁电话?
const wait = (duration = 0) => {
return new Promise((resolve) => {
setTimeout(resolve, duration);
});
};
const asyncTask1 = () => {
return wait(1000).then(() => {
console.log('task1 takes 1s.');
});
};
const asyncTask2 = () => {
return wait(3000).then(() => {
console.log('task2 takes 3s.');
});
};
Promise.resolve()
.then(() => {
asyncTask1();
})
.then(() => {
asyncTask2();
})
.catch(() => {
console.log('fail.');
});

如代码所示,asyncTask2
在asyncTask1
完成之前不会运行。但问题是如果asyncTask1
失败,我该如何停止链调用。即asyncTask2
因为asyncTask1
失败而无法运行
。
注意:asyncTask1中没有生成错误或异常,我想使用状态(成功或失败)来决定asyncTask1的结果。
Q2。当我使用Promise.all()时,如何知道哪个任务会生成异常?
const wait = (duration=0) => {
return new Promise((resolve) => {
setTimeout(resolve, duration);
});
};
const asyncTask1 = () => {
return wait(1000).then(() => {
console.log('task1 takes 1s.');
});
};
const asyncTask2 = () => {
return wait(3000).then(() => {
console.log('task2 takes 3s.');
});
};
Promise
.all([asyncTask2(), asyncTask1()])
.then(() => {
console.log('all done.');
})
.catch((e) => {
console.log('error');
});

上面的代码可以成功运行,但如果asyncTask1
或asyncTask2
失败,它将进入catch函数。所以问题是如何知道异常是来自asyncTask1
还是asyncTask2
?
答案 0 :(得分:0)
您可以使用Array.prototype.map()
来调用数组中设置的函数,throw
index
在.map()
回调.catch()
内发生错误的const wait = (duration=0) => {
return new Promise((resolve) => {
setTimeout(resolve, duration);
});
};
const asyncTask1 = () => {
return wait(1000).then(() => {
console.log('task1 takes 1s.');
});
};
const asyncTask2 = () => {
return wait(3000).then(() => {
throw new Error()
console.log('task2 takes 3s.');
});
};
let arr = [asyncTask2, asyncTask1];
Promise
.all(arr.map((p, index) =>
p().catch(err => {throw new Error(err + " at index " + index)})))
.then(() => {
console.log('all done.');
})
.catch((e) => {
console.log('error', e);
});
{{1}}