Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the Asynchronous problem in JavaScript

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to solve the asynchronous problem in JavaScript". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to solve asynchronous problems in JavaScript.

I. the evolutionary history of asynchronous solutions

The asynchronous operation of JavaScript has always been a hassle, so people keep coming up with a variety of solutions. It can be traced back to the earliest callback function (ajax old friend), to Promise (not a new friend), to ES6's Generator (strong friend).

We may have used a famous Async.js a few years ago, but it didn't get rid of the callback function, and the error handling followed the convention that "the first parameter of the callback function is used to pass the error." The well-known callback hell was still a prominent problem until Generator changed this asynchronous style.

But with the advent of ES7's async await (bunker's new friend), we can easily write synchronous-style code while having an asynchronous mechanism, which is arguably the simplest, most elegant and best solution so far.

II. Async await grammar

The syntax of async await is relatively simple and can be regarded as the grammatical sugar of Generator, which is more semantic than asterisks and yield. The following is a simple example of outputting hello world after 1 second:

Function timeout (ms) {return new Promise ((resolve) = > {setTimeout (resolve, ms);});} async function asyncPrint (value, ms) {await timeout (ms); console.log (value)} asyncPrint ('hello world', 1000)

Await can only be used in async functions. If it is used in ordinary functions, an error will be reported.

Await is followed by a Promise object (of course, other values are fine, but it will be wrapped as an immediate resolve Promise, which makes no sense)

Await will wait for the result of Promise to return before continuing execution.

Although await is waiting for the Promise object, you don't have to write .then (), you can get the return value directly. Fine-tune the above code and find that the return value result can also output hello world:

Function timeout (ms) {return new Promise ((resolve) = > {setTimeout (_ = > {resolve ('hello world')}, ms);} async function asyncPrint (ms) {let result = await timeout (ms); console.log (result)} asyncPrint (1000)

III. Async await error handling

As mentioned earlier, although await waits for a Promise object, it doesn't have to write .then (), so instead of writing .catch (), you can catch errors directly with try catch, which can avoid redundant and cumbersome error handling code, so fine-tune the above example:

Function timeout (ms) {return new Promise ((resolve, reject) = > {setTimeout (_ = > {reject ('error')}, ms); / / reject simulation error, return error});} async function asyncPrint (ms) {try {console.log (' start'); await timeout (ms); / / error console.log ('end') returned here; / / so this code will not be executed} catch (err) {console.log (err) / / error error}} asyncPrint (1000) caught here

If you have more than one await, you can put it together in the try catch:

Async function main () {try {const async1 = await firstAsync (); const async2 = await secondAsync (); const async3 = await thirdAsync ();} catch (err) {console.error (err);}}

4. Pay attention to async await

1)。 As mentioned earlier, the running result of the Promise object after the await command is likely to be reject or logical error, so it is best to put the await in the try catch code block.

2)。 The asynchronous operation of multiple await commands, if there is no dependency, let them trigger at the same time.

Const async1 = await firstAsync (); const async2 = await secondAsync ()

In the above code, if async1 and async2 are two separate asynchronous operations, it will be time-consuming to write in this way, because secondAsync will not be executed until the firstAsync is completed, which can be handled gracefully with Promise.all:

Let [async1, async2] = await Promise.all ([firstAsync (), secondAsync ()])

3)。 Await can only be used in async functions. If it is used in ordinary functions, an error will be reported:

Async function main () {let docs = [{}, {}]; / / await is only valid in async function docs.forEach (function (doc) {await post (doc); console.log ('main');});} function post () {return new Promise ((resolve) = > {setTimeout (resolve, 1000);});}

Just add async to the forEach internal method:

Async function main () {let docs = [{}, {}]; docs.forEach (async function (doc) {await post (doc); console.log ('main');});} function post () {return new Promise ((resolve) = > {setTimeout (resolve, 1000);});}

But you will find that three main are output at the same time, which means that post is executed concurrently, not secondary execution. Changing to for can solve the problem. The output of the three main is one second apart:

Async function main () {let docs = [{}, {}, {}]; for (let doc of docs) {await post (doc); console.log ('main');}} function post () {return new Promise ((resolve) = > {setTimeout (resolve, 1000);}); at this point, I believe you have a better understanding of "how to solve asynchronous problems in JavaScript". Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report