JavaScript, async and await keywords

Magus
1,130 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Take a look at the following code and run it.

Asynchronous code using await and async
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function job() {
return new Promise(function(resolve, reject) {
setTimeout(resolve, 500, 'Hello world 1');
});
}
async function test() {
let message = await job();
console.log(message);
return 'Hello world 2';
}
test().then(function(message) {
console.log(message);
});
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Let's examine what is going on here:

The async keyword at line 7 means that the function test will always return a promise. Even if the function just executes a simple return 'Hello world'. It will be converted to a promise no matter what. That's why we can use a then at line 14 to print the message.

The await keyword at line 8 means that the code execution will stop until the promise returned by job() is resolved. And the return value from test() is stored in the message variable.

And that's all. It's very simple to understand async and await when you already know how promises work. If you have a hard time understanding this, we can rewrite the test function in plain promise style:

function test() {
    return job().then(function(message) {
        console.log(message);

        return 'Hello world 2';
    });
}
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content