Async/Await in ECMAScript

Create new Javascript file named demo1.js. This file contains code demo as below:

async function process() {

    let promise = new Promise((resolve, reject) => {
        setTimeout(() => resolve("Done!"), 1000)
    });

    let result = await promise;

    console.log(result);
}

process();




Use node demo1.js statement run code demo

Done!

Create new Javascript file named demo2.js. This file contains code demo as below:

function calculateAfter2Sec(param) {
    return new Promise((resolve, reject) => {
        setTimeout(function () {
            resolve(param * 2);
        }, 2000);
    });
}

async function sum(a, b) {
    a = await calculateAfter2Sec(a);
    b = await calculateAfter2Sec(b);
    return a + b;
}

sum(1, 2).then(console.log);

Use node demo2.js statement run code demo

6