AsyncGenerator.prototype.throw()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itâs been available across browsers since 2020å¹´1æ.
throw() 㯠AsyncGenerator ã¤ã³ã¹ã¿ã³ã¹ã®ã¡ã½ããã§ããããã throw æãã¸ã§ãã¬ã¼ã¿ã¼æ¬ä½ã®ä¸ã®åæ¢ä¸ã®ä½ç½®ã«æ¿å
¥ããããã®ããã«åä½ããã¨ã©ã¼ç¶æ
ãã¸ã§ãã¬ã¼ã¿ã¼ã«éç¥ãã¦ãã¨ã©ã¼ãå¦çããããã¯ãªã¼ã³ã¢ãããå®è¡ãã¦ããèªèº«ãéãããã¨ãã§ãã¾ãã
æ§æ
asyncGeneratorObject.throw(exception)
弿°
è¿å¤
çºçããã¨ã©ã¼ãææã§ããªãå ´åã¯ã渡ãããä¾å¤ã§æå¦ãã Promise ãè¿ãã¾ãã
ä¾å¤ã try...catch ã§æããããåéãã¦ã¸ã§ãã¬ã¼ã¿ã¼ã次ã®å¤ãçæããã¨ã次㮠2 ã¤ã®ããããã£ãæã¤ Object ã§è§£æ±ºãã Promise ãè¿ãã¾ãã
ä¾
>throw() ã®ä½¿ç¨
次ã®ä¾ã§ã¯ãåç´ãªã¸ã§ãã¬ã¼ã¿ã¼ã¨ãthrow ã¡ã½ããã使ç¨ãã¦çºçããã¨ã©ã¼ã«ã¤ãã¦ç¤ºãã¾ããã¨ã©ã¼ã¯ãé常éã try...catch ãããã¯ã§æããããã¨ãã§ãã¾ãã
// éåæã¿ã¹ã¯ã§ããå®éã«ã¯ãã£ã¨æçãªãã¨ã使ç¨ãã¦ãããã¨ã
// æ³å®ãã¦ãã ããã
function sleep(time) {
return new Promise((resolve, reject) => {
setTimeout(resolve, time);
});
}
async function* createAsyncGenerator() {
while (true) {
try {
await sleep(500);
yield 42;
} catch (e) {
console.error(e);
}
}
}
const asyncGen = createAsyncGenerator();
asyncGen.next(1).then((res) => console.log(res)); // { value: 42, done: false }
asyncGen
.throw(new Error("Something went wrong")) // Error: Something went wrong
.then((res) => console.log(res)); // { value: 42, done: false }
仿§æ¸
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-asyncgenerator-prototype-throw> |