5.3 ES6 async Function
Category ES6 Tutorial
async
async is a keyword related to asynchronous operations introduced in ES7, closely associated with Promise and Generator.
Syntax
async function name([param[, param[, ... param]]]) { statements }
name: Function name.
param: The name of the parameter to be passed to the function.
statements: The function body.
Return Value
An async function returns a Promise object, to which callback functions can be added using the then method.
async function helloAsync(){
return "helloAsync";
}
console.log(helloAsync()) // Promise {<resolved>: "helloAsync"}
helloAsync().then(v=>{
console.log(v); // helloAsync
})
An async function may contain an await expression, which pauses the execution of the async function until the await expression completes. Once the asynchronous operation is complete, the async function resumes execution and returns the resolved value.
The await keyword is only valid inside an async function. Using await outside an async function will result in a syntax error.
function testAwait(){
return new Promise((resolve) => {
setTimeout(function(){
console.log("testAwait");
resolve();
}, 1000);
});
}
async function helloAsync(){
await testAwait();
console.log("helloAsync");
}
helloAsync();
// testAwait
// helloAsync
await
The await operator is used to wait for a Promise. It can only be used inside an async function.
Syntax
[return_value] = await expression;
- expression: A Promise object or any value to wait for.
Return Value
Returns the fulfillment value of the Promise. If the value is not a Promise, it returns the value itself.
If a Promise is passed to an await operator, await will wait for the Promise to resolve and then return its resolved value.
function testAwait (x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function helloAsync() {
var x = await testAwait ("hello world");
console.log(x);
}
helloAsync ();
// hello world
Normally, the await command is followed by a Promise object, but it can also be followed by other values such as strings, booleans, numbers, or regular functions.
function testAwait(){
console.log("testAwait");
}
async function helloAsync(){
await testAwait();
console.log("helloAsync");
}
helloAsync();
// testAwait
// helloAsync
The await operator handles different expressions as follows:
Promise object: await pauses execution and waits for the Promise to resolve, then resumes the async function's execution and returns the resolved value.
Non-Promise object: Returns the corresponding value directly.
#
-
** Mantianfeiyu
* 176**[email protected]
async function a(){
console.log("1")
console.log("2")
}
a()
console.log("3")
// Prints: 1 2 3
Using await for testing:
async function a(){
await 1
console.log("1")
console.log("2")
}
a()
console.log("3")
// Prints: 3 1 2
** Mantianfeiyu
* 176**[email protected]
-
** Kandy
* 474**[email protected]
function getApiData() {
// Promise is a solution for asynchronous programming
// The first parameter is the callback when the Promise is fulfilled, the second is the callback when it is rejected
return new Promise((resolve, reject) => {
// Simulate delay (fetching data from the server)
setTimeout(() => {
// Fulfillment
resolve({name: 'kandy', age: 99})
}, 3000)
})
}
let user = {}
async function getUser() {
// Execute
await getApiData().then(res => {
user = res
})
// This block of code will be blocked until getApiData is executed and then completes its work
console.log('Data retrieval completed: ', user)
}
getUser() // Asynchronous method
console.log('Starting data retrieval:') // This is non-blocking (synchronous code)
Result:
Starting data retrieval:
After 3 seconds:
Data retrieval completed: {name: 'kandy', age: 99}
** Kandy
* 474**[email protected]
** Click to Share Notes
-
-
-
-2.2 ES6 Destructuring Assignment
- 5.3 ES6 async Function
Follow on WeChat
English: