


The difference between js asynchronous callback Async/Await and Promise, 6 reasons why Async/Await replaces 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()
Using Async/Await is like this:
const makeRequest = async () => { console.log(await getJSON()) return "done"}makeRequest()
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) => { // 代码 })
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) }}
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) }}
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 } })}
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 }}
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) }) })}
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) })}
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)}
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) })
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) })
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
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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 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 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

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

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 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

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
