In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "the method tutorial of using async await in JS". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Catalogue
JQuery's $. Ajax
The beginning of the Webpack era
Learn more about Promise
Eliminate nesting
Await-to-js
Summary
JQuery's $. Ajax
Before we begin, let's talk about my js async path. When I was still in school, when I was still in the jQuery world, the asynchronous operation that I came into contact with directly and often used was the network request. Ajax went all over the world, and accompanied me for almost half a year from sophomore to graduation.
Done (function () {/ / success!)! Do something... ) .fail (function () {/ / fail!! Do something... }) .always (function () {/ / loading finished.. });
Undeniably, $. Ajax works well, and in the face of only one request in most scenarios, it is completely competent and even feels great
But there is a big problem, that is, it will be particularly bad in the face of the request chain, for example, one request depends on the result of another request, two may not matter, if there are five or eight, they may want to commit suicide directly.
Done (function () {/ / success!!) Do something... Done (function () {/ / success!!) Do something... Done (function () {/ / success!!) Do something... Done (function () {/ / success!!) Do something... Done (function () {/ / success!!) Do something... / / more... ) .fail (function () {/ / fail!! Do something... }) .always (function () {/ / loading finished.. );) .fail (function () {/ / fail! Do something... }) .always (function () {/ / loading finished.. );) .fail (function () {/ / fail! Do something... Done (function () {/ / success!!) Do something... Done (function () {/ / success!!) Do something... / / more.... ) .fail (function () {/ / fail!! Do something... }) .always (function () {/ / loading finished.. );) .fail (function () {/ / fail! Do something... }) .always (function () {/ / loading finished.. });}) .always (function () {/ / loading finished.. );) .fail (function () {/ / fail! Do something... }) .always (function () {/ / loading finished.. );) .fail (function () {/ / fail! Do something... }) .always (function () {/ / loading finished.. });
I'm sorry. I didn't know you could cover so many layers. But the fact is that such a process often occurs in TM. Let's talk about it, can you blame the product? I can only blame myself for not being good at learning.
Chain operation like this, I think, is that individuals may be routed, not to mention the readability of the code, for example, the product requirements that are changing every day. Perhaps request 2 and request 3 were followed by request 1 immediately after the end of request 1, followed by a big wave of the product. I think this process is not right, and then it becomes request 2, request 3, request 1, how to change this Nima nesting doll? Some people may wonder, why not use axios, await, async? I have to mention that the project code was written in JSP in 2008. After taking a shit on the shit for more than half a year, I ushered in a big turnaround. The newly written project began to transfer to Vue, and gave up some compatibility. I TM directly took off.
The beginning of the Webpack era
The new project directly Vue + Webpack, I directly arrange axios, await, async, now the code is very good, the nesting N-tier code is gone
Const R1 = await doSomthing1 (); if (r1.xxx = 1) {const R2 = await doSomthing2 (R1); const R3 = await doSomthing3 (R2); / / do something....} else {const R4 = await doSomthing4 (R1); const R5 = await doSomthing5 (R4); / / do something....} / / do something....
But there is a problem with the above code. If a task reports an error, the code terminates directly. This is not in line with our expectations, so let's add try catch.
Let r1try do something... {R1 = await doSomthing1 ();} catch (e) {/ / do something... Return;} if (R1) {if (r1.xxx = 1) {let R2; try {R2 = await doSomthing2 (R1);} catch (e) {/ / do something... Return;} if (R2) {let R3; try {R3 = await doSomthing3 (R2);} catch (e) {/ / do something... Return;} / / do something... }} else {let R4; try {R4 = await doSomthing4 (R1);} catch (e) {/ / do something... Return;} if (R4) {let R5; try {R5 = await doSomthing5 (R4);} catch (e) {/ / do something... Return;}} / / do something... } / / do something...}
???
If you optimize, you don't optimize.
At this time, I think the smart buddy might say, what kind of pancakes is this? And the dull little friend has begun to think about how to solve such a problem.
Learn more about Promise
Let's take a look at the definition of Promise
/ * * Represents the completion of an asynchronous operation * / interface Promise {/ * Attaches callbacks for the resolution and/or rejection of the Promise. * @ param onfulfilled The callback to execute when the Promise is resolved. * @ param onrejected The callback to execute when the Promise is rejected. * @ returns A Promise for the completion of which ever callback is executed. * / then (onfulfilled?: ((value: t) = > TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) = > TResult2 | PromiseLike) | undefined | null): Promise; / * Attaches a callback for only the rejection of the Promise. * @ param onrejected The callback to execute when the Promise is rejected. * @ returns A Promise for the completion of the callback. * / catch (onrejected?: ((reason: any) = > TResult | PromiseLike) | undefined | null): Promise;}
Both then and catch will return a new Promise. I'm sure many friends have figured out how to solve the problem. We need to use try catch because it will report an error, so why don't we just return a result that will never be wrong? Just do it.
Eliminate nesting
Function any (promise) {return promise.then ((v) = > v). Catch ((_) = > null);}
So it's completely solved, huh? By judging whether there is a value to determine whether it is successful, there is no need to write try catch, but this kind of code does not work well. If then returns a void, then the calf is over, a undefined and a null, which also judges a hammer. Let's improve it again.
Function any (promise) {return promise. Then (v) = > ({ok: v, hasErr: false}) .catch ((e) = > ({err: e, hasErr: true}));}
If you use it
Const r = await any (doSomething ()); if (r.hasErr) {console.log (r.err); return;} console.log (r.ok)
Does it look perfect now? hurry up and sell it to your buddies.
Buddy:? This pancake thing, no need.
Me: the one I wrote, which is easy to use in asynchronism, bid farewell to nested try catch, Barabala.
Buddy: OK, I'll use it next time.
We must have encountered such a situation, we write code to look down on each other, as long as it is not a tripartite library, everyone can write without colleagues. No, no, no.
Await-to-js
I thought I was the only one to appreciate this elegance. Things took a turn for the better. One day I was browsing github and found something similar to me. Await-to-js, a few lines of code revealed the same persistence as me.
/ / here is the latest code / * @ param {Promise} promise * @ param {Object=} errorExt-Additional Information you can pass to the err object * @ return {Promise} * / export function to (promise: Promise, errorExt?: object): Promise {return promise .then (data: t) = > [null, data]) .catch ((err: U) = > {if (errorExt) {Object.assign (err, errorExt) } return [err, undefined];});} export default to
And then paste the use example.
Import to from 'await-to-js';// If you use CommonJS (i.e NodeJS environment), it should be:// const to = require (' await-to-js'). Default;async function asyncTaskWithCb (cb) {let err, user, savedTask, notification; [err, user] = await to (UserModel.findById (1)); if (! user) return cb ('No user found') [err, savedTask] = await to (TaskModel ({userId: user.id, name: 'Demo Task'}); if (err) return cb (' Error occurred while saving task'); if (user.notificationsEnabled) {[err] = await to (NotificationService.sendNotification (user.id, 'Task Created')); if (err) return cb (' Error while sending notification') } if (savedTask.assignedUser.id! = = user.id) {[err, notification] = await to (NotificationService.sendNotification (savedTask.assignedUser.id, 'Task was created for you')); if (err) return cb (' Error while sending notification');} cb (null, savedTask);} async function asyncFunctionWithThrow () {const [err, user] = await to (UserModel.findById (1)); if (! user) throw new Error ('User not found') } this is the end of the tutorial on how to use async await in JS. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.