Graduate Program KB

Async Await

  • Async and Await provides an easier way to deal with promises
  • Solves multiple callbacks and promise chaining

Async Functions

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();

  • await keyword needs to be inside of a async function
  • (Currently I think), Javascript has no way of cancelling a async operation

Async Generators with Yield

  • async* ... yield await
  • yield for pushing, and await for pulling
    async function* foo() {
    yield await Promise.resolve('a');
    yield await Promise.resolve('b');
    yield await Promise.resolve('c');
    }

    let str = '';

    async function generate() {
    for await (const val of foo()) {
        str = str + val;
    }
    console.log(str);
    }

    generate();

Async Iterations

  • Using the for await loop
  • Doesn't work with async iterators that are no async iterables
    async function* foo() {
    yield 1;
    yield 2;
    }

    (async function() {
    for await (const num of foo()) {
        console.log(num);
        // Expected output: 1

        break; // Closes iterator, triggers return
    }
    })();