In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "what are the common mistakes in using promise", the content is simple and clear, and I hope it can help you solve your doubts. Let the editor lead you to study and learn this article "what are common mistakes in using promise?"
Promise provides an elegant way to handle asynchronous operations in JS. This is also the solution to avoid "callback hell". However, not many developers know about it. Therefore, many people often make mistakes in practice.
1. Avoid Promise hell
Usually, Promise is used to avoid callback hell. But abusing them can also cause Promise to be hell.
UserLogin ('user') .then (function (user) {getArticle (user) .then (function (articles) {showArticle (articles) .then (function () {/ / Your code goes here...) });)
In the above example, we nested three promise for userLogin, getararticle, and showararticle. This complexity will grow in proportion to lines of code, and it may become unreadable.
To avoid this, we need to unnest the code, return getArticle from the first then, and then process it in the second then.
UserLogin ('user'). Then (getArticle). Then (showArticle). Then (function () {/ / Your code goes here...})
two。 Using try/catch blocks in Promise
Typically, we use try/catch blocks to handle errors. However, it is not recommended to use try/catch in Promise objects.
This is because if there are any errors, the Promise object is automatically handled within the catch.
Ew Promise ((resolve, reject) = > {try {const data = doThis (); / / do something resolve ();} catch (e) {reject (e);}}) .then (data = > console.log (data)) .catch (error = > console.log (error))
In the above example, we used the try/catch block within Promise.
However, Promise itself catches all errors (even typos) within its scope without the need for try/catch blocks. It ensures that all exceptions thrown during execution are taken and converted to a rejected Promise.
New Promise ((resolve, reject) = > {const data = doThis (); / / do something resolve ()}) .then (data = > console.log (data)) .catch (error = > console.log (error))
Note: it is critical to use .catch () blocks in Promise blocks. Otherwise, your test case may fail, and the application may crash during production.
3. Using asynchronous functions within Promise blocks
Async/Await is a more advanced syntax for dealing with multiple Promise in synchronized code. When we use the async keyword before a function declaration, it returns a Promise, and we can use the await keyword to stop the code until the Promise we are waiting for is resolved or rejected.
However, when you put an Async function in a Promise block, there will be some side effects.
Suppose we want to do an asynchronous operation in the Promise block, so we use the async keyword, but unfortunately our code throws an error.
In this way, even if we use the catch () block or wait for your Promise inside the try/catch block, we can't deal with the error immediately. Take a look at the example below.
/ / this code cannot handle errors new Promise (async () = > {throw new Error ('message');}) .catch (e = > console.log (e.message)); (async () = > {try {await new Promise (async ()) = > {throw new Error (' message');});} catch (e) {console.log (e.message);}}) ()
When I encounter the async function within the Promise block, I try to keep the async logic out of the Promise block to keep it synchronized. 9 out of 10 times were successful.
However, in some cases, an async function may be required. In this case, there is no choice but to manage it manually with try/catch blocks.
New Promise (async (resolve, reject) = > {try {throw new Error ('message');} catch (error) {reject (error);}}) .catch (e = > console.log (e.message)); / / using async/await (async () = > {try {await new Promise (async (resolve, reject) = > {try {throw new Error (' message');} catch (error) {reject (error)) }});} catch (e) {console.log (e.message);}}) ()
4. Execute the Promise block immediately after the Promise is created
As for the following code snippet, if we put the code snippet where the HTTP request is called, it will be executed immediately.
Const myPromise = new Promise (resolve = > {/ / code to make HTTP request resolve (result);})
The reason is that this code is wrapped in a Promise constructor. However, some people may think that it is triggered only after the then method of myPromise is executed.
However, this is not the case. In contrast, when a Promise is created, the callback is executed immediately.
This means that by the time the myPromise is established and reaches the following line, the HTTP request is probably already running, or at least in a scheduled state.
Promises is always eager to execute the process.
But what should I do if I want to perform Promises later? What if I don't want to make a HTTP request now? Is there any magic mechanism built into Promises that allows us to do this?
The answer is to use functions. Function is a time-consuming mechanism. They will be executed only if the developer explicitly calls them with (). Simply defining a function doesn't give us anything. So the most effective way to make Promise lazy is to wrap it in a function!
Const createMyPromise = () = > new Promise (resolve = > {/ / HTTP request resolve (result);})
For HTTP requests, the Promise constructor and callback functions are called only when the function is executed. So now we have a lazy Promise that only executes when we need it.
5. Do not necessarily use the Promise.all () method
If you've been working for years, you already know what I'm talking about. If there are many unrelated Promise, we can deal with them at the same time.
Promise are concurrent, but if you wait for them one by one, it will take too much time, and Promise.all () can save a lot of time.
Remember, Promise.all () is our friend const {promisify} = require ('util'); const sleep = promisify (setTimeout); async function f1 () {await sleep (1000);} async function f2 () {await sleep (2000);} async function f3 () {await sleep (3000);} (async () = > {console.time (' sequential'); await F1 (); await f2 (); await f3 (); console.timeEnd ('sequential');}) ()
The execution time of the above code is about 6 seconds. But if we replace it with Promise.all (), it will reduce the execution time.
(async () = > {console.time ('concurrent'); await Promise.all ([F1 (), f2 (), f3 ()]); console.timeEnd (' concurrent');}) (); these are all the contents of the article "what are the common mistakes in using promise". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.