loading
open in
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// ECMAScript 2017
const john = {
    firstName: 'John',
    lastName: 'Stone',
    dob: 1970,
};

function getAge(user) {
    return new Promise((resolve, reject) => {
        const now = new Date();
        resolve(now.getFullYear() - user.dob);
    });
}

async function getFullname(user) {
    return new Promise((resolve, reject) => {
        const now = new Date();
        resolve(`${user.firstName} ${user.lastName}`);
    });
}

async function getUserSummary() {
    let user = john;
    //Inside async function we can await to invoke another async/promise function
    // The excution will pause until awaiting function return value.
    const age = await getAge(user);
    
    //This code is for demonstration popup only.
    const fullName = await getFullname(user);

    return {
        firstName: user.firstName,
        lastName: user.lastName,
        fullName,
        age,
    }
}

//async function also return a promise so we can utilize it as a promise to get result as below.
getUserSummary().then((result) => {
    console.log(result);
});

setTimeout(() => {}, 1000);
Native Browser JavaScript