async and await

As a further language enhancement when working with promises, TypeScript introduces two keywords that work together when using promises. These two keywords are async and await. The usage of async and await can best be described by considering some sample code, as follows:

function awaitDelayed() : Promise<void> { 
    return new Promise<void> ( 
        ( resolve: () => void, 
          reject: () => void ) =>  
          { 
             function afterWait() { 
                 console.log(`calling resolve`); 
                 resolve(); 
             }     
             setTimeout(afterWait, 1000); 
          } 
    ); 
}

We start with a fairly standard function named awaitDelayed that returns a promise, similar to the examples that we have seen before. Note that in the body of the afterWait function, we log a message to the console before calling the resolve callback. Let's now take a look at how we can use this promise with the async and await keywords, as follows:

async function callAwaitDelayed() { 
    console.log(`call awaitDelayed`); 
    await awaitDelayed(); 
    console.log(`after awaitDelayed`); 
} 
 
callAwaitDelayed(); 

We start with a function named callAwaitDelayed that is prefixed by the async keyword. Within this function, we log a message to the console, and then call the previously defined awaitDelayed function. This time, however, we prefix the call to the awaitDelayed function with the keyword await. We then log another message to the console. The output of this code is as follows:

call awaitDelayed
calling resolve
after awaitDelayed

What this output is showing is that the await keyword is actually waiting for the asynchronous function to be called before continuing on with the program execution. This produces an easy-to-read, and easy-to-follow flow of program logic by automatically pausing execution until the promise is fulfilled.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.131.72