这种“问题”与生成器本身无关,它仅与 try..catch 块内的 await 机制有关,因为 每当在 try-catch 块内拒绝承诺时, catch 已加入(除非承诺单独尝试捕获)。
事实上,生成器不能再进一步了,因为一旦以某种方式到达catch,它就会一直持续到另一个yield 被调用。如果不需要调用任何东西,它只会完成提供done: true,这就是生成器的预期行为。
您的主要问题是,您希望生成器产生所有值,但它只是不能,因为yield 块从未达到 :
try {
const thing = await fetchThing()
const otherThing = await fetchAnother()
yield { // <-- never met if either thing or otherThing are rejected.
...thing,
...otherThing
}
} catch (error) { // <-- this block is reached whenever either thing or otherThing raise an exception.
console.log('Error happened, but thats ok, I want to continue')
}
如果您希望 try..catch 块在任一内部可等待元素引发异常时继续,您还需要尝试捕获它们,以便您可以进一步控制它们的“失败”行为:
try {
let thing, otherThing;
try {
thing = await fetchThing()
otherThing = await fetchAnother()
}
catch (innerException) {
console.log('either of the above failed!', innerException);
}
// in this way, the below block will be reached.
yield {
...thing,
...otherThing
}
} catch (error) {
console.log('Error happened, but thats ok, I want to continue')
}
这样,无论两者都失败还是都成功,yield 块将到达并继续执行。
这是一个显示上述内容的示例:
const fakeAsync = async () => await Promise.resolve(true);
const fakeAsyncReject = async () => await Promise.reject(false);
async function* getAll(someStuff) {
try {
let res, raiseExc;
try {
res = await fakeAsync();
}
catch (innerResException) {
console.log('an inner exception raised.');
}
try {
raiseExc = await fakeAsyncReject();
}
catch (innerRaiseException) {
console.log('an inner exception was raised.', innerRaiseException);
}
// yield block, always reached unless there is something really wrong in this try block, like syntax errors or whatever.
yield {
res,
raiseExc
}
}
catch (error) {
// catch block raised only when the try block above yields an exception, NOT raised when either of the try-catch blocks inside the try-catch actually join the catch.
console.log('Error happened', error);
}
}
// Uncomment this block if you want to see how the for-await would work.
/*
(async() => {
for await (var res of getAll([])) {
console.log('res is', res);
}
})();
*/
(async() => {
const asyncIterator = getAll([]);
console.log(await asyncIterator.next());
})();