Easy Tutorial
❮ Android Tutorial Sharedpreferences Tencent Open Source ❯

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 }

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;

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:

#

-

** 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

Cancel

-

-

-

-1.1 ES6 Tutorial

-1.2 ES6 Environment Setup

-2.1 ES6 let and const

-2.2 ES6 Destructuring Assignment

-2.3 ES6 Symbol

-3.1.1 ES6 Map and Set

-3.1.2 ES6 Reflect and Proxy

-3.2.1 ES6 Strings

-3.2.2 ES6 Numbers

-3.2.3 ES6 Objects

-3.2.4 ES6 Arrays

-4.1 ES6 Functions

-4.3 ES6 Class

-4.4 ES6 Modules

-5.1 ES6 Promise Object

-5.2 ES6 Generator Function

Follow on WeChat

English:

❮ Android Tutorial Sharedpreferences Tencent Open Source ❯