This article refers to the article :

Reprint please indicate that it is from : Grape city official website , Grape city provides professional development tools for developers 、 Solutions and services , Enabling developers .

ES2017 The standard has been established in 2017 year 6 It was officially finalized in September , And broad support for the latest features : An asynchronous function . If you've ever been asynchronous JavaScript The logic perplexity of , This new function is designed for you .

Asynchronous functions more or less allow you to write some sequential JavaScript Code , But it doesn't have to be callbacks、generators or promise It contains your logic .

The following code :

function logger() {
let data = fetch('')

This code doesn't live up to your expectations . If you are JS Writing in the , Then you may know why .

Here's the code , But it did what you expected .

async function logger() {
let data = await fetch('')

This code works , Intuitively , Just a lot async and await Two words .

ES6 Before the standard JavaScript An asynchronous function

In-depth learning async and await Before , We need to understand Promise. In order to understand Promise, We need to go back to the normal callback function to learn more .

Promise Is in ES6 Introduced in , And promote the writing of JavaScript Asynchronous code aspect of , It's a huge improvement . Since then, writing callback functions is not so painful .

A callback is a function , You can pass the result to a function and call it inside that function , In response to an event . meanwhile , This is also JS The basis of .

function readFile('file.txt', (data) => {
// This is inside the callback function

This function simply records data to a file , It's impossible to read a file before it's finished . The process seems simple , But if you want to read and record five different files in order , How does it need to be implemented ?

No, Promise When , In order to perform tasks in sequence , It needs to be implemented through nested callbacks , Like the following code :

// This is officially callback hell
function combineFiles(file1, file2, file3, printFileCallBack) {
let newFileText = ''
readFile(string1, (text) => {
newFileText += text
readFile(string2, (text) => {
newFileText += text
readFile(string3, (text) => {
newFileText += text

It's hard to infer what's going on under the function , At the same time, it's hard to deal with errors in various scenarios , For example, if one of the files does not exist .

Promise Improved the situation

That's exactly what it is. Promise The advantage of ,Promise It's a kind of reasoning about data that hasn't been generated yet .Kyle Simpson take Promise Interpreted as : It's like ordering in a fast food restaurant .

  • Order
  • Pay for the lunch you ordered , And get the queue number
  • Waiting for lunch
  • When your lunch is ready , I'll call your order number to remind you to pick up your meal
  • Got lunch

Like the scene above , When you're waiting for a meal , You can't have lunch , But you can prepare for lunch ahead of time . You can do other things , Now you know that lunch is coming , Even though you can't enjoy it yet , But this lunch has “promise” Here you are . That's what's called promise, An object that represents data that will eventually exist .

.then((file1-data) => { /* do something */ })
.then((previous-promise-data) => { /* do the next thing */ })
.catch( /* handle errors */ )

It's on it Promise  grammar . Its main advantage is that it can link queue events together in an intuitive way . Although this example is clear and easy to understand , But there are callbacks .Promise It just makes callbacks simpler and more intuitive .

best mode :async / await

A few years ago ,async The function incorporates JavaScript The ecological system . Just last month ,async The function becomes JavaScript The official nature of language , And there's a lot of support .

async and await It's based on Promise and generator On . Essentially , Allow us to use await This keyword pauses anywhere we want in any function .

async function logger() {
// pause until fetch returns
let data = await fetch('')

After the above code runs , Get the results you want . Code from API Data is recorded in the call .

The advantage of this approach is that it's very intuitive . The way you write code is the way your brain thinks , Tell the script to pause where it needs to .

Another benefit is , When we can't use promise when , You can also use try and catch:

async function logger () {
try {
let user_id = await fetch('/api/users/username')
let posts = await fetch('/api/`${user_id}`')
let object = JSON.parse(user.posts.toString())
} catch (error) {
console.error('Error:', error)

The above is an example of deliberate error , To prove a point : At run time ,catch You can catch errors in any step . There are at least three places ,try May fail , This is one of the cleanest ways to handle errors in asynchronous code .

We can also use... With loops and conditions async function :

async function count() {
let counter = 1
for (let i = 0; i < 100; i++) {
counter += 1
await sleep(1000)

This is a very simple example , If you run this program , You'll see the code in sleep Pause on call , The next iteration of the loop will take place in 1 Start in seconds .

Key points and details

I believe we have felt asyns and await The beauty of , Let's take a closer look at the details :

  • async and await Based on the Promise above . Use async, Always return one Promise. Remember that , Because it's also a mistake prone place .
  • When executed await when , The program pauses the current function , Not all the code
  • async and await It's non blocking
  • Still usable Promise helpers, for example Promise.all( )

As in the previous example :

async function logPosts () {
try {
let user_id = await fetch('/api/users/username')
let post_ids = await fetch('/api/posts/<code>${user_id}')
let promises = => {
return fetch('/api/posts/${post_id}')
let posts = await Promise.all(promises)
} catch (error) {
console.error('Error:', error)
  • await Can only be used to declare as async The function of
  • therefore , Cannot use... In a global context await

The following code :

// throws an error
function logger (callBack) {
console.log(await callBack)
} // works!
async function logger () {
console.log(await callBack)

Now available

To 2017 year 6 month , Almost all browsers can use async and await. To make sure your code is always available , You need to use Babel Put your JavaScript The code compiles to a syntax that old browsers also support .

If it's for more ES2017 I'm interested in the content , Please visit ES2017 A complete list of features .

Related reading :

【 Report benefits broadcast 】100 More than one set of report templates are free to download

One of the most popular 5 A front-end frame comparison

2017 Front end framework 、 Class library 、 Tool competition

Angular vs React The most comprehensive and in-depth comparison

ES2017 Asynchronous functions are now officially available in more related articles

  1. More elegant way : JavaScript Execute asynchronous functions sequentially in

    Fire is asynchronous 1995 year , The most popular browser of the time -- Start running in Netscape JavaScript ( Originally known as LiveScript). 1996 year , Microsoft released JScript compatible JavaScript. With Netscape . tiny ...

  2. 『 careful 』.Net4.6 Task An asynchronous function Than Synchronization function slow 5 times Experience of stepping on a pit

    asynchronous Task Brief introduction This title is a little grandstanding , You don't mind ( I don't rule out the problem of personal technical ability ) —— Next : I will use a small Demo hold The thought of this article is clear . .Net 4.0 And then there is Task function —— Asynchronous editing ...

  3. 14. Concurrency and asynchrony - 3.C#5.0 The asynchronous function of -《 Nutshell c#》

    14.5.2 Write asynchronous functions private static readonly Stopwatch Watch = new Stopwatch(); static void Main(string[] a ...

  4. Net4.6 Task An asynchronous function Than Synchronization function slow 5 times Experience of stepping on a pit

    Net4.6 Task An asynchronous function Than Synchronization function slow 5 times Experience of stepping on a pit asynchronous Task Simple ...

  5. Asynchronous control --- Implementation function asyncAll, In the array after execution func1,func2,func3 After asynchronous function , Output “end”

    Implementation function asyncAll, In the array after execution func1,func2,func3 After asynchronous function , Output "end" function func1(callback) { setTimeout ...

  6. Node.js use ES6 Native Promise Encapsulating asynchronous functions

    Promise The concept of Promise Object is used for asynchronous (asynchronous) Calculation .. One Promise An object represents an unfinished object , But what is expected to be done in the future . Promise Several states of : pending: first ...

  7. Asynchronous function encapsulation, please ensure the asynchrony (Javascript Good habits that need to be developed )

    Background hypothesis : You have a lot of configuration information stored on the server , Because there are too many configurations , I don't want to write all the configuration information to the front end every time , I hope I can get it when I need it . because Javascript Single thread running , You don't want to get blocked ui So you specialize in ...

  8. GCD, With synchronization / An asynchronous function , Create concurrency / Serial queue

    queue   The first parameter :C Language string , label The second parameter : DISPATCH_QUEUE_CONCURRENT: Concurrent queues DISPATCH_QUEUE_SERIAL: Serial queue dispatch_queue_ ...

  9. C# Async/Await Asynchronous function principle

    principle Compared to synchronous functions ,CLR There are several different characteristics when executing asynchronous functions : 1.         Not all at once , And it's done many times 2.         Not done by the same thread , Instead, the thread pool dynamically allocates one thread at a time to process : combination ...

Random recommendation

  1. C++ Class template

    In the last article (C++ Function templates ) in , It mainly introduces C++ Function templates in , Similar to a function , Classes can also be parameterized by one or more types . Container class is a typical example of this feature , This paper addresses : ...

  2. python digital image processing (6): Batch processing of images

    Sometimes , We don't just have to deal with a picture , Maybe a batch of pictures will be processed . Now , We can perform processing through loops , Can also call the program's own set of images to deal with . The picture set function is : ...

  3. Use python stay SAE Build a wechat application on the Internet , Use the translation of Tao api Translate online

    1. Get ready , First use python Build wechat public platform step by step ( One ) After basically realizing the function of automatic reply , Then apply for one in Youdao dictionary key, ...

  4. URAL 1160 Network( Minimum spanning tree )

    Network Time limit: 1.0 secondMemory limit: 64 MB Andrew is working as system administrator and is p ...

  5. ( 7、 ... and ) Study CSS And filter attribute

    filter: alpha(opacity=,finishopacity=,style=)??? alpha It's about transparency , Its basic attribute is filter:alpha(opacity,finishopa ...

  6. POJ 1001 Exponentiation

    The question : seek c Of n The next power …… All decimals are required …… solution : At first I only knew that there was BigInteger……java Large number + simulation . Write for the first time java Large number …… All kinds of errors, all kinds of exception……ORZ There is no forerunner 0 And the place after the decimal ...

  7. Make a little progress every day --JS Medium getYear()

    It's what I met in the project these two days , Maybe it's simple , But for the first time , Make a note of . Use... On the page JS Got the current date , And use getYear() Method returns the current year ,2013 Also no problem , Code in IE After all the tests are passed, submit ...

  8. [ assembly language ]- Chapter vii. SI and DI

    1- SI and DI yes 8086CPU neutralization bx Registers with similar functions , SI and DI Can't be divided into two 8 Bit register , The following three sets of instructions perform the same function : (1)  mov bx,0 mov ax,[bx] (2) m ...

  9. [PA 2014]Kuglarz

    Description There are... On the magician's desk n A line of cups , The number is 1,2,…,n, Some of the cups have a small ball under them , If you can guess exactly which cups , You can get the prize . cost c_ij element , The magician will tell you the cup i,i+ ...

  10. HSV Color space and color component range

    Part of it comes from : ...