async

async is a keyword related to asynchronous operations that was only introduced in ES7, and it is closely related to Promise and Generator.

Syntax

async function name([param[, param[, ... param]]]) { statements }
  • name: The function name.
  • param: The names of the parameters to be passed to the function.
  • statements: The function body statements.

Return Value

An async function returns a Promise object, and you can use the then method to add callback functions.

async function helloAsync(){ return "helloAsync"; } console.log(helloAsync()) // Promise {<resolved>: "helloAsync"} helloAsync().then(v=>{ console.log(v); // helloAsync })

An async function may contain await expressions. When an async function is executed, if it encounters await, it pauses execution first, and resumes the async function and returns the resolved value after the triggered asynchronous operation completes.

The await keyword is only valid within an async function. If you use await outside an async function body, you will only get 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 object, and 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 processing result of the Promise object. If what is being awaited is not a Promise object, the value itself is returned.

If a Promise is passed to an await operator, await will wait for the Promise to complete normally and return its processing result.

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, and ordinary functions.

function testAwait(){ console.log("testAwait"); } async function helloAsync(){ await testAwait(); console.log("helloAsync"); } helloAsync(); // testAwait // helloAsync

The way await handles different expressions following it:

  • Promise object: await pauses execution, waits for the Promise object to resolve, then resumes the async function and returns the resolved value.
  • Non-Promise object: directly returns the corresponding value.