JavaScript, async and await keywords
Magus
40.1K views
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);
});
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';
});
}
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.