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 use the Async function

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to use the Async function". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

The Async function is a great thing and will be supported by default in Chrome 55. It allows you to write promise-based code, but it looks like synchronized code and does not block the main thread. So, it makes your asynchronous code look less "smart" but more readable.

Code example for the Async function:

Async function myFirstAsyncFunction () {try {const fulfilledValue = await promise;} catch (rejectedValue) {/ / … }}

If you use the async keyword before a function declaration, you can use await within that function. When you go to await a promise, this function will be paused in a non-blocking manner until the promise is in settled state. If the Promise returns a successful status, you will get a return value, and if a failed status is returned, the failed message will be thrown.

Tip: if you are not familiar with promises, please check our promises guide

Example 1: print response information

Suppose we want to request a URL and print out the response information. Here is the sample code that uses promise:

Function logFetch (url) {return fetch (url) .then (response = > response.text ()) .then (text = > {console.log (text);}) .catch (err = > {console.error ('fetch failed', err);});}

Let's use the async function to achieve the same function:

Async function logFetch (url) {try {const response = await fetch (url); console.log (await response.text ());} catch (err) {console.log ('fetch failed', err);}}

You can see that the number of lines of code is the same as in the previous example, but using the async function makes all the callback functions missing! This makes our code very easy to read, especially for those who are not particularly familiar with promise.

Tip: any value of your await is passed through Promise.resolve (), so you can safely use a non-local promise.

The return value of the Async function

Whether you use await inside a function or not, the Async function always returns a promise. When the async function returns any value, the returned promise will call the resolve method, and when the async function throws an exception error, the returned promise will call the reject method, so:

/ / wait ms milliseconds function wait (ms) {return new Promise (r = > setTimeout (r, ms));} async function hello () {await wait (500); return 'world';}

When hello () is executed, a success status is returned, and the value passed is promise. World.

Async function foo () {await wait (500); throw Error ('bar');}

When hello () is executed, a failure state is returned and the value passed is promise of Error ('bar').

Example 2: response flow

In more complex cases, the async function is more advantageous. Suppose we want to turn the chunks data into a response stream when recording it and return the final message length.

Hint: "recording chunks" makes me feel awkward.

Here is how to use promise:

Function getResponseSize (url) {return fetch (url) .then (response = > {const reader = response.body.getReader (); let total = 0; return reader.read () .then (function processResult (result) {if (result.done) return total; const value = result.value; total + = value.length; console.log ('Received chunk', value); return reader.read (). Then (processResult);})}) }

Take a good look. I'm Jake Archibald, the "underground party" of promise. See how I call processResult inside it and set up an asynchronous loop? Writing like this makes me feel "very smart". But like most "smart" code, you have to stare at it for a long time to figure out what it's doing, like those magic eye photos in the 1990s. Quote

Let's rewrite the above function with the async function:

Async function getResponseSize (url) {const response = await fetch (url); const reader = response.body.getReader (); let result = await reader.read (); let total = 0; while (! result.done) {const value = result.value; total + = value.length; console.log ('Received chunk', value); / / get the next result result = await reader.read ();} return total;}

All the "smart" code is gone. Now the new asynchronous loop is replaced by a reliable, plain-looking while loop, which makes me feel very neat. What's more, in the future, we will use async iterators, which will use for of loops instead of while loops, which will be cleaner!

Hint: I have a favorable opinion of streams. If you are not familiar with streams, you can read my guide.

Other syntax of the Async function

We've seen how async function () {} is used, but the async keyword can also be used in other function syntax.

Arrowhead function

/ / map some URLs to json-promises const jsonPromises = urls.map (async url = > {const response = await fetch (url); return response.json ();})

Tip: array.map (func) doesn't care whether you give an async function or not, it just treats it as a normal function that returns promise. Therefore, the execution of the second callback does not wait for the await processing in the * callbacks to complete.

Object method

Const storage = {async getAvatar (name) {const cache = await caches.open ('avatars'); return cache.match (`/ avatars/$ {name} .jpg`);}}; storage.getAvatar (' jaffathecake') .then (…)

Class method

Class Storage {constructor () {this.cachePromise = caches.open ('avatars');} async getAvatar (name) {const cache = await this.cachePromise; return cache.match (`/ avatars/$ {name} .jpg`);}} const storage = new Storage (); storage.getAvatar (' jaffathecake'). Then (…)

Tip: the constructors and getters/settings of a class cannot be async functions.

Be careful! Please avoid putting too much emphasis on order

Although the code you are writing appears to be synchronized, make sure you don't miss out on parallel processing.

Async function series () {await wait (500); await wait (500); return "done!";}

The above code requires 1000ms to complete, however:

Async function parallel () {const wait1 = wait; const wait2 = wait; await wait1; await wait2; return "done!";}

The above code only requires 500ms, because the two wait are processed at the same time.

Example 3: sequentially output request information

Suppose we want to take a series of URL responses and print them out in the correct order as soon as possible.

Take a deep breath. Here is the code to implement it using promise:

Function logInOrder (urls) {/ / fetch all the URLs const textPromises = urls.map (url = > {return fetch (url). Then (response = > response.text ();}); / / log them in order textPromises.reduce ((chain, textPromise) = > {return chain.then (() = > textPromise). Then (text = > console.log (text));}, Promise.resolve ();}

Yeah, this has achieved its goal. I'm using reduce to deal with a string of promise. I'm too smart. This is such a "smart" code, but let's not do it.

However, when converting the above code to using the async function, it looks so sequential that it can confuse us:

:-1: not recommended-too much emphasis on priority

Async function logInOrder (urls) {for (const url of urls) {const response = await fetch (url); console.log (await response.text ());}}

It looks much cleaner, but my second request will not be sent until the * requests have been fully processed, and so on. This is much slower than the example of promise above. Fortunately, there is a neutral solution:

: + 1: recommended-good and parallel

Async function logInOrder (urls) {/ / fetch all the URLs in parallel const textPromises = urls.map (async url = > {const response = await fetch (url); return response.text ();}); / / log them in sequence for (const textPromise of textPromises) {console.log (await textPromise);}}

In this example, all url are requested and processed one by one, but the 'smart' reduce is replaced by standard, normal, and more readable for loop loops.

Browser compatibility and solution

As of this writing, Chrome 55 already supports the async function by default. But in all major browsers, it is still under development:

Edge-In build 14342 + behind a flag

Firefox-active development

Safari-active development

Solution 1:Generators

All major browsers support generators. If you are using them, you can polyfill the async function a little bit.

Babel can do these things for you, and here's an example written through Babel REPL-does it feel familiar with the converted code? This transformation mechanism is part of Babel's es2017 preset.

Tip: Babel REPL is a very interesting thing, try it.

I suggest you do this now, because when your target browser supports the async function, you just need to remove Babel from your project. But if you really don't want to use the conversion tool, you can use Babel's polyfill to click Preview.

Async function slowEcho (val) {await wait (1000); return val;}

When you use the polyfill click preview mentioned above, you can replace the above code with:

Const slowEcho = createAsyncFunction (function* (val) {yield wait (1000); return val;})

Notice that you pass a generator (function*) to the createAsyncFunction function, and then use yield instead of await. Besides, they have the same effect.

Solution 2: regenerator

If you want to be compatible with older browsers, Babel can also convert generators so that you can use async functions in browsers above IE8, but you need to use Babel's es2017 preset and the es2015 preset

You will see that the converted code does not look good, so please be careful of code expansion.

Async all the things!

Once all browsers support the async function, use async on all functions that return promise! Because it not only makes your code more tider, but it also ensures that the async function always returns a promise.

This is the end of the content of "how to use Async function". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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

Development

Wechat

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

12
Report