[JavaScript] async function and async function*
async function
An async function declaration creates an AsyncFunction object. Each time when an async function is called, it returns a new Promise which will be resolved with the value returned by the async function, or rejected with an exception uncaught within the async function.
Example of async function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function resolveAfter2Seconds() { return new Promise((resolve) => { setTimeout(() => { resolve("resolved"); }, 2000); }); } async function asyncCall() { console.log("calling"); const result = await resolveAfter2Seconds(); console.log(result); // Expected output: "resolved" } asyncCall(); | cs |
async function*
An async function* declaration creates an AsyncGeneratorFunction object. Each time when an async generator function is called, it returns a new AsyncGenerator object, which conforms to the async iterator protocol. Every call to next() returns a Promise that resolves to the iterator result object.
An async generator function combines the features of async functions and generator functions. You can use both the await and yield keywords within the function body. This empowers you to handle asynchronous tasks ergonomically with await, while leveraging the lazy nature of generator functions.
Example of async function*
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | async function* myGenerator(step) { await new Promise((resolve) => setTimeout(resolve, 10)); yield 0; yield step; yield step * 2; } const gen = myGenerator(2); gen .next() .then((res) => { console.log(res); // { value: 0, done: false } return gen.next(); }) .then((res) => { console.log(res); // { value: 2, done: false } return gen.next(); }) .then((res) => { console.log(res); // { value: 4, done: false } return gen.next(); }) .then((res) => { console.log(res); // { value: undefined, done: true } return gen.next(); }); | cs |
0 댓글