Home Web Front-end JS Tutorial The difference between js asynchronous callback Async/Await and Promise, 6 reasons why Async/Await replaces Promise

The difference between js asynchronous callback Async/Await and Promise, 6 reasons why Async/Await replaces Promise

Sep 12, 2018 pm 04:45 PM
js promise

This chapter will introduce to you the difference between Async/Await and Promise in js asynchronous callback, and 6 reasons why Async/Await replaces Promise. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

What is Async/Await?

async/await is a new way of writing asynchronous code. The previous methods were callback functions and Promise.

async/await is implemented based on Promise and cannot be used for ordinary callback functions.

async/await, like Promise, is non-blocking.

async/await makes asynchronous code look like synchronous code, which is its magic.

Async/Await syntax

In the example, the getJSON function returns a promise, which will return a JSON object when the promise is successfully resolved. We just call this function, print the returned JSON object, and return "done".

Using Promise is like this:

const makeRequest = () =>
  getJSON()
    .then(data => {
      console.log(data)
      return "done"
    })makeRequest()
Copy after login

Using Async/Await is like this:

const makeRequest = async () => {
  console.log(await getJSON())
  return "done"}makeRequest()
Copy after login

They have some slight differences:

There are more functions in front An aync keyword. The await keyword can only be used within functions defined by aync. The async function will implicitly return a promise, and the resolve value of the promise is the value of the function return. (The reosolve value in the example is the string "done")

Point 1 implies that we cannot use await in the outermost code because it is not within the async function.

// 不能在最外层代码中使用
awaitawait makeRequest()
// 这是会出事情的 
makeRequest().then((result) => {
  // 代码
 })
Copy after login

await getJSON() means that console.log will wait until the promise of getJSON is successfully resolved before executing it.

Why Async/Await is better?

1. Simplicity

As can be seen from the example, using Async/Await obviously saves a lot of code. We don't need to write .then, we don't need to write anonymous functions to handle the resolve value of Promise, we don't need to define redundant data variables, and we avoid nested code. These small advantages add up quickly, as will become more apparent in the code examples that follow.

2. Error handling

Async/Await allows try/catch to handle both synchronous and asynchronous errors. In the promise example below, try/catch cannot handle the JSON.parse error because it is inside the Promise. We need to use .catch so that the error handling code is very redundant. Moreover, our actual production code will be more complicated.

const makeRequest = () => {
  try {
    getJSON()
      .then(result => {
        // JSON.parse可能会出错
        const data = JSON.parse(result)
        console.log(data)
      })
      // 取消注释,处理异步代码的错误
      // .catch((err) => {
      //   console.log(err)
      // })
  } catch (err) {
    console.log(err)
  }}
Copy after login

If aync/await is used, catch can handle JSON.parse errors:

const makeRequest = async () => {
  try {
    // this parse may fail
    const data = JSON.parse(await getJSON())
    console.log(data)
  } catch (err) {
    console.log(err)
  }}
Copy after login

3. Conditional statement

In the following example, data needs to be obtained and then returned based on the data Decide whether to return directly or continue to obtain more data. ·

const makeRequest = () => {
  return getJSON()
    .then(data => {
      if (data.needsAnotherRequest) {
        return makeAnotherRequest(data)
          .then(moreData => {
            console.log(moreData)
            return moreData          })
      } else {
        console.log(data)
        return data      }
    })}
Copy after login

These codes give me a headache just looking at them. It's easy to get confused with nesting (6 levels), parentheses, and return statements that just need to pass the final result to the outermost Promise.

Writing the above code using async/await can greatly improve readability:

const makeRequest = async () => {
  const data = await getJSON()
  if (data.needsAnotherRequest) {
    const moreData = await makeAnotherRequest(data);
    console.log(moreData)
    return moreData  } else {
    console.log(data)
    return data    
  }}
Copy after login

4. Intermediate value

You have probably encountered such a scenario, calling promise1, use the result returned by promise1 to call promise2, and then use the results of both to call promise3. Your code is likely to look like this:

const makeRequest = () => {
  return promise1()
    .then(value1 => {
      return promise2(value1)
        .then(value2 => {        
          return promise3(value1, value2)
        })
    })}
Copy after login

If promise3 does not require value1, you can simply nest the promise flat. If you can't stand nesting, you can put value 1 & 2 into Promise.all to avoid deep nesting:

const makeRequest = () => {
  return promise1()
    .then(value1 => {
      return Promise.all([value1, promise2(value1)])
    })
    .then(([value1, value2]) => {      
      return promise3(value1, value2)
    })}
Copy after login

This method sacrifices semantics for readability. There is no reason to put value1 and value2 in an array other than to avoid nesting.

If you use async/await, the code will become extremely simple and intuitive.

const makeRequest = async () => {
  const value1 = await promise1()
  const value2 = await promise2(value1)
  return promise3(value1, value2)}
Copy after login

5. Error stack

In the following example, multiple Promises are called. Assume that an error is thrown somewhere in the Promise chain:

const makeRequest = () => {
  return callAPromise()
    .then(() => callAPromise())
    .then(() => callAPromise())
    .then(() => callAPromise())
    .then(() => callAPromise())
    .then(() => {
      throw new Error("oops");
    })}makeRequest()
  .catch(err => {
    console.log(err);
    // output
    // Error: oops at callAPromise.then.then.then.then.then (index.js:8:13)
  })
Copy after login

Return from the Promise chain The error stack gives no clue as to where the error occurred. Even worse, it's misleading; the only function in the error stack is called callAPromise, which has nothing to do with the error. (The file name and line number are still useful).

However, the error stack in async/await will point to the function where the error is located:

const makeRequest = async () => {
  await callAPromise()
  await callAPromise()
  await callAPromise()
  await callAPromise()
  await callAPromise()
  throw new Error("oops");}makeRequest()
  .catch(err => {
    console.log(err);
    // output
    // Error: oops at makeRequest (index.js:7:9)
  })
Copy after login

In a development environment, this advantage is not big. However, it will be very useful when you analyze the error log of the production environment. At this time, it is better to know that the error occurred in makeRequest than to know that the error occurred in the then chain.

6. Debugging

The last and most important point is that async/await can make code debugging easier. 2 reasons why debugging Promises is a pain:

1) You cannot set breakpoints in arrow functions that return expressions

The difference between js asynchronous callback Async/Await and Promise, 6 reasons why Async/Await replaces Promise

2) If you Set a breakpoint in the .then code block and use the Step Over shortcut key. The debugger will not jump to the next .then because it will only skip the asynchronous code.

When using await/async, you no longer need so many arrow functions, so you can skip await statements just like debugging synchronous code

The difference between js asynchronous callback Async/Await and Promise, 6 reasons why Async/Await replaces Promise

Conclusion

Async/Await is one of the most revolutionary features added to JavaScript in recent years. It will make you realize how bad Promise syntax is, and provide an intuitive alternative.

concern

Maybe you have some reasonable doubts about Async/Await:
It makes asynchronous code less obvious: we are used to using callback functions or .then to identify asynchronous code, and it may take us several weeks to get used to the new flag. However, C# has had this feature for many years, and friends who are familiar with it should know that the temporary inconvenience is worth it.
Node 7 is not an LTS (long-term support release): however, Node 8 will be released next month, and migrating your code to the new version will be very simple.

The above is the detailed content of The difference between js asynchronous callback Async/Await and Promise, 6 reasons why Async/Await replaces Promise. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Keeping your word: The pros and cons of delivering on your promises Keeping your word: The pros and cons of delivering on your promises Feb 18, 2024 pm 08:06 PM

In daily life, we often encounter problems between promises and fulfillment. Whether in a personal relationship or a business transaction, delivering on promises is key to building trust. However, the pros and cons of commitment are often controversial. This article will explore the pros and cons of commitments and give some advice on how to keep your word. The promised benefits are obvious. First, commitment builds trust. When a person keeps his word, he makes others believe that he is a trustworthy person. Trust is the bond established between people, which can make people more

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

See all articles