Async/await is the way to simplify JavaScript code

Source: Internet
Author: User

Translator by: Among the 6 reasons for replacing Promise in async/await, we compared two different asynchronous programming methods:async/await and Promise, and this blog will introduce the example code How the async/await simplifies JavaScript code.

    • Original: Async/await'll make YOUR CODE SIMPLER
    • Translator: Fundebug

In order to ensure readability, this paper uses free translation rather than literal translation. In addition, the copyright of this article belongs to the original author, translation is only used for learning.

async/await is a new feature of JavaScript ES7 , derived from . NET and C #. It can write asynchronous code without callback functions like those of synchronous code. This blog will use some code examples to illustrate how async/await simplifies JavaScript code.

1. Removing the callback function

Running the sample code for this article does not require an additional library of functions. For the latest versions of mainstream browsers, such as Chrome,firefox, Safari, and Edge, they all support the async/await syntax. In addition, the async/await syntax is supported by node. JS 7.6+.

We have written some simple API interfaces for simulating asynchronous operations. These interfaces all return promise and resolve some data after 200ms.

class Api { Constructor () {This.user = { id: 1, name: ' Test '} this.friends = [ this.user, this.user, This.user] This.photo = ' not a real photo ' } getUser () {return new Promise ((resolve, reject) = { SetTimeout (() = Resolve (this.user), (+)})} getfriends (UserId) {return new Promise ((resolve, reject) = { SetTimeout (() = Resolve (this.friends.slice ()), (+)})} Getphoto (UserId) {return new Promise ((resolve, reject) = { SetTimeout (() = Resolve (this.photo), (+)})} ThrowError () {return new Promise ((resolve, reject) = { SetTimeout (() = Reject (new error (' intentional error ')), })}}
Nesting Promise
function Callbackhell () {Const API = New API ()letuser, friends Api.getuser (). Then (function (returneduser) {user = Returneduserapi.getfriends (user.id). Then ( function (returnedfriends) {friends = Returnedfriendsapi.getphoto (user.id). Then ( function (photo) {console.log (' Callbackhell ', {user, friends, photo})})}

Developers who have used promise to write callback functions must not be unfamiliar, so the nesting of layers of code usually ends like this:

})})})}

Call the callback function in the callback function, layer by layer nesting, this is called "Callback Hell". In real code, such cases are not uncommon and often more complex.

Chain-type Promise
function Promisechain ( const API = new Api () let user, Friends api.getuser (). Then ( (returneduser) = = { user = Returneduser return api.getfriends (user.id) }). Then ( (returnedfriends) = = { friends = returnedfriends< span class= "keyword" >return api.getphoto (user.id) }). Then ( ( console.log ( })}

One of the best features of promise is that you can return a new promise in the then callback function, so that you can link these promise together with only one level of nesting. chained promise are much simpler than nested promise , but still a lot of redundancy.

Async/await

Is it OK to not use a callback function? Of course! With async/await , 7 lines of code can be done.

Async function asyncawaitisyournewbestfriend () {Const API = New API () Const user = await api.getuser ()Const FRIENDS = await api.getfriends (user.id) Const PHOTO = await Api.getphoto (user.id)console.log (' Asyncawaitisyournewbestfriend ', {user, friends, photo})}

When you use the await keyword, the assignment will wait until the end of the asynchronous operation. In this way, it looks like synchronous code, and the actual execution is actually asynchronous.

2. Simplify the cycle

async/await can make complex operations, such as loops, easier. For example, what should we do if we need to get a list of all the Friends friends for a user?

Using Promise
function promiseloops () { Const API = New API () Api.getuser (). Then ((user) = { return Api.getfriends (user.id)}). Then ((returnedfriends) = { Const Getfriendsoffriends = (friends) + = {if (Friends.length > 0) { Let friend = Friends.pop ()return Api.getfriends (friend.id). Then ((morefriends) = { console.log (' promiseloops ', morefriends) return Getfriendsoffriends (Friends)})}}return Getfriendsoffriends (returnedfriends)})}

We used the recursive function getfriendsoffriends to get friends-of-friends, knowing that the friends array was empty. Such a simple task, it is obviously too complicated to write.

When implemented using Promise.all () , it is not a loop, but is executed concurrently.

Using async/await

This could is so much easier.

Async function asyncawaitloops () {Const API = New API () Const USER = await api.getuser ()Const FRIENDS = await api.getfriends (user.id) For (letfriend of friends) {letmorefriends = await api.getfriends (friend.id) console.log (' asyncawaitloops ', morefriends)}}

At this point, you can directly use the for loop to implement, very simple.

3. Simplifying concurrency

Using loops to get friends-of-friends is obviously too slow to take concurrency easier.

async function asyncawaitloopsparallel ( const API = new API () const user = await api.getuser () const friends = await api.getfriends (user.id) const friendpromises = Friends.map (friend = Api.getfriends (friend.id)) const morefriends = Await promise.all (friendpromises) console.log ( ' Asyncawaitloopsparallel ', morefriends) }

In order to implement concurrency, you only need to use the Promise array as an argument to the Promise.all () . This way, you only need to await a promise, and this promise will resolveat the end of all concurrent operations.

4. Simplifying error handling using callback functions to handle promise errors
function Callbackerrorhell () { Const API = New API () Let user, friendsApi.getuser (). Then (function (returneduser) { user = Returneduserapi.getfriends (user.id). Then (function (returnedfriends) { Friends = Returnedfriendsapi.throwerror (). Then (function () { console.log (' Error is not thrown ') Api.getphoto (user.id). Then (function (photo) { console.log (' Callbackerrorhell ', {user, friends, photo}) },function (err) { Console.error (Err)})},function (err) { Console.error (Err)})},function (err) { Console.error (Err)})},function (err) { Console.error (Err)})}

This is very bad, the code is very redundant, and the readability is poor.

Handling promise errors using the Catch method
function Callbackerrorpromisechain () { Const API = New API () Let user, friendsApi.getuser (). Then ((returneduser) = { user = Returneduserreturn Api.getfriends (user.id)}). Then ((returnedfriends) = { Friends = Returnedfriendsreturn Api.throwerror ()}). Then (() = {console.log (' Error is not thrown ') return Api.getphoto (user.id)}). Then ((photo) = { console.log (' Callbackerrorpromisechain ', {user, friends, photo}) }). catch ((Err) = { Console.error (Err)})}

It's much better to handle all the errors at the end of the promise chain, using the Catch method.

Handling async/await errors using Try/catch
async function Span class= "title" >aysncawaittrycatch ( try { const API = new API () span class= "keyword" >const user = await api.getuser () Const FRIENDS = await api.getfriends (user.id)  await Api.throwerror () console.log (  const photo = await api.getphoto (user.id) Span class= "built_in" >console.log ( ' async/await ', {user, friends, photo}) } catch (err) { console.error (Err) }}

For async/await code, it is easier to work with Try/catch and synchronize the code.

If you need to monitor the error of the JavaScript code on the line, you can use Fundebug's real-time error monitoring service for free, just one line of code to get it done!

5. Simplify Code organization

Functions defined with the async keyword return Promise, which makes it easier to organize your code.

For example, in the previous example, we could return the user information we obtained instead of printing it directly; then we could get the user information by returning the promise.

Async function GetUserInfo () { Const API = New API () Const USER = await api.getuser () Const FRIENDS = await api.getfriends (user.id) Const PHOTO = await Api.getphoto (user.id) return {User, friends, photo}}function Promiseuserinfo () { GetUserInfo (). Then (({user, friends, photo}) = { console.log (' Promiseuserinfo ', {user, friends, photo}) })}

Using the async/await syntax is much simpler:

Async function awaituserinfo () {const {User, friends, photo} = await Getuse Rinfo ()console.log (' Awaituserinfo ', {user, friends, photo})}

How can I get more information about the user?

Async function getlotsofuserdata () {Const users = []while( Users.length < ) {Users.push (await GetUserInfo ())}console.log (' Getlotsofuserdata ', users)}

How does concurrency work? How do I handle errors?

Async function getlotsofuserdatafaster () {try {const userpromises = Array (+). Fill (GetUserInfo ()) Const users = await promise.all (userpromises) console.log (' Getlotsofuserdatafaster ', users)} catch (Err) {console.error (Err)}}

Copyright NOTICE: Please specify the author fundebug and this address:https://blog.fundebug.com/2017/10/16/async-await-simplify-javascript/

Async/await simplifies JavaScript code in this way

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.