Home > Article > Web Front-end > What is the usage of await in es6?
In es6, await is used to wait for an asynchronous request of a promise. After the asynchronous operation is completed, the execution of the async function is resumed. This keyword can only be used in "async function", and the syntax is "async function(){ await=Asynchronous request that returns promise}".
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
The syntax is:
async function(){await=返回promise的异步请求}
await is an operator used to form expressions. The result of await expression depends on its etc. thing. If it is waiting for a Promise object, wait for the Promise object to resolve, and then get the value of resolve as the result of the await expression. The sync function call will not cause blocking. All blocking inside it is encapsulated in a Promise object and executed asynchronously.
There may be await expressions in the async function. When the async function is executed, if it encounters await, the execution will be suspended first. After the triggered asynchronous operation is completed, the execution of the async function will be resumed and the parsed value will be returned.
await keyword is only valid in async function. If you use await outside an async function, you'll just get a syntax error.
Return value
Returns the processing result of the Promise object. If something other than a Promise object is awaited, the value itself is returned.
If a Promise is passed to an await operator, await will wait for the Promise to be processed normally and return its processing result.
Examples are as follows:
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, which can also be followed by other values, such as strings, Boolean values, numerical values, and ordinary functions.
[Related recommendations: javascript video tutorial, web front-end】
The above is the detailed content of What is the usage of await in es6?. For more information, please follow other related articles on the PHP Chinese website!