Promise versus await syntax

As a refresher of promise versus async await syntax, let's compare these two techniques side by side. Firstly, let's examine the then and catch syntax used by standard promises:

function simplePromises() { 
    delayedPromise().then( 
        () => {  
            // execute on success 
        } 
    ).catch ( 
        () => { 
            // execute on error 
        } 
    ); 
    // code here does NOT wait for async call 
} 

Note that in the preceding promise code, we are using .then and .catch to define anonymous functions to be called depending on whether the asynchronous call was successful or not. Another caveat when using promise syntax is that any code outside of the .then or .catch block will be executed immediately, and will not wait for the asynchronous call to complete.

Secondly, let's examine the new async await syntax :

async function usingAsyncSyntax() { 
    try { 
        await delayedPromise(); 
        // execute on success 
    } catch(error) { 
        // execute on error 
    } 
    // code here waits for async call 
} 

Here, our async await syntax allows for a very simple syntax that flows logically. We know that any call to await will block code execution until the asynchronous function has returned, including any code defined outside our try...catch block.

As can be seen by comparing the two styles side by side, using the async await syntax simplifies our code, makes it more human readable, and, as such, less error prone.

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

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