mirror of
https://github.com/alrayyes/wiki.git
synced 2024-11-25 04:56:23 +00:00
795 B
795 B
id | title |
---|---|
3dac2b04-4015-4c1f-847c-5e677aec1fc0 | JavaScript For Await Of |
Syntax
async function f() {
for await (const x of createAsyncIterable(["a", "b"])) {
console.log(x);
}
}
// Output:
// a
// b
Rejections
Like await
in async
functions, th eloop throws
an exception if next()
returns a rejection:
function createRejectingIterable() {
return {
[Symbol.asyncIterator]() {
return this;
},
next() {
return Promise.reject(new Error("Problem!"));
},
};
}
(async function () {
// (A)
try {
for await (const x of createRejectingIterable()) {
console.log(x);
}
} catch (e) {
console.error(e);
// Error: Problem!
}
})(); // (B)