Get the App
SLTechnology News&Howtos  ›  Development  › 

How to program asynchronously with Async and Await in ES7

Shulou Source: shulou.com Published: 2022-06-03 13:59:01 09月22日 Update

This article introduces how to use Async and Await in ES7 for asynchronous programming, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Basic rules of Async/Await

Async indicates that this is an async function, and await can only be used in this function.

Await means to wait here for promise to return the result before continuing with execution.

Await should be followed by a promise object (of course, the other return values don't matter, but they will be executed immediately, but that would be meaningless. )

An example of Async/Await

Async/Await should be the simplest asynchronous solution so far. Let's take a look at an example first.

Here we want to implement a pause function, enter N milliseconds, then pause N milliseconds before continuing.

Var sleep = function (time) {return new Promise (function (resolve, reject) {setTimeout (function () {resolve ();}, time);})}; var start = async function () {/ / use here as intuitive as synchronous code console.log ('start'); await sleep (3000); console.log (' end');}; start ()

The console first outputs start, then waits for 3 seconds to output end.

Get the return value

Await waits for a promise object, but you don't have to write .then (..) to get the return value directly.

Var sleep = function (time) {return new Promise (function (resolve, reject) {setTimeout (function () {/ / return 'ok' resolve (' ok');}, time);})}; var start = async function () {let result = await sleep (3000); console.log (result); / / received 'ok'}

Catch error

Since. Then (..) No need to write, so .catch (..) You don't have to write either, and you can catch errors directly with standard try catch syntax.

Var sleep = function (time) {return new Promise (function (resolve, reject) {setTimeout (function () {/ / Simulation error, return 'error' reject (' error');}, time);})}; var start = async function () {try {console.log ('start'); await sleep (3000) / / an error is returned here / / so the following code will not be executed console.log ('end');} catch (err) {console.log (err); / / error `error`} was caught here

Cycle through multiple await

Await looks like synchronous code, so it can be written in a for loop without having to worry about problems that used to require closures to solve.

.. Omit the above code var start = async function () {for (var I = 1; I)

Tags: Errors code functions content help loops programming up and down context no examples objects more synchronization demonstration output good intuitive of course it doesn't matter Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Apple Shulou Tech Info NVidia vpn