Friday, July 13, 2018

JavaScript Async/Await Reminder

Overview 

C# and JavaScript async/await provide the same feature dealing with asynchronous calls.
But the details are not the same.

Here is an article that talk about it
Comparing asynchronous patterns between C# and JavaScript

Code Sample

Here is a sample in NodeJs v 9.2, that show case why async/await is cleaner than nested Promises.
But it is important to understand what really happen behind the scene. See my comments.
/*
    Code sample based from 
        JavaScript ES 2017: Learn Async/Await by Example
        Brandon Morelli
        https://codeburst.io/javascript-es-2017-learn-async-await-by-example-48acc58bad65
*/

/* Nested asynchronous function with Promises */

function doubleAfter2Seconds(x) {
    return new Promise(resolve => {
        setTimeout(() => { resolve(x * 2); }, 1000);
    });
}
    
function addPromise(x){
    return new Promise(resolve => {
        doubleAfter2Seconds(10).then((a) => {
            doubleAfter2Seconds(20).then((b) => {
                doubleAfter2Seconds(30).then((c) => {
                    resolve(x + a + b + c);
                })
            })
        })
    });
}

console.log(`starting big async calculation with Promise`);

addPromise(5).then( (result) => {
    console.log(`big async calculation result:${result}`);
});


/* Nested asynchronous function with async/await */

console.log(`starting big async calculation async/await`);

/*
    The function addAsync does not return the result of the expression: x + a + b + c,
    as the code imply.

    Because the function is marked with the word async, the function
    really return a Promise.

    The line `return x + a + b + c;` will be executed if the promise succeed and the 
    value will be passed as the parameter of the method resolve().
*/
async function addAsync(x) {
    
    const a = await doubleAfter2Seconds(10); // Shortcut syntax to avoid to attach a 
                                             // then() and store the resolved value 
                                             // of the Promise in the variable a
    const b = await doubleAfter2Seconds(20);
    const c = await doubleAfter2Seconds(30);
    return x + a + b + c;
};

async function main() {

    // Long syntax to call an async method using a then().
    addAsync(5).then(
        (result) => {  /* result contains x + a + b + c */
            console.log(`big async calculation async/await result:${result}`);
        }
    );

    // Shortcut syntax to avoid to attach a then()
    const r = await addAsync(5);
    console.log(`big async calculation async/await r:${r}`);
}

main();


No comments:

Post a Comment