Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is Promise in JavaScript

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail what Promise is in JavaScript. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

What is Promise in JavaScript?

Imagine that you are interviewing a candidate for a position in your company.

A young man crazily came in for an interview. When his interview was about to begin, he realized that he had forgotten his resume.

Scoundrel, right?

However, he was not discouraged. Fortunately, he had a roommate who was still at home at that time.

He quickly called his roommate over the phone and asked him for help. He begged his roommate to help find his resume. His roommate promised to text him back as soon as he had anything to report.

Assuming he finally finds his resume, he can reply by text message:

"it worked. I found your resume!"

But if he doesn't find it, he should send back a failure message explaining why he can't find his resume. For example, he might send this message to a friend who is interviewing:

"Sorry, I can't find your resume because the key to your safe is missing."

Meanwhile, the interview went ahead as planned, and the interviewer insisted on finding the promise of the resume instead of the actual resume. At this point, the interviewer sets the status of the resume to PENDING.

The interviewee answered all the questions he was asked. But in the final analysis, his employment still depends on the final status of his resume.

His roommate finally texted back. As we discussed before, if he doesn't find his resume, he will share with you the failure and the reasons why he didn't find it.

When this happens, the interview will be over and the interviewer will be rejected.

On the other hand, if the roommate finds a resume, he will happily tell his friends that he has succeeded, and he will move on to realize his hope of finding a job.

So how does this translate into JS code?

The roommate whose resume is found and texted by promise is synonymous with how we define promise in JavaScript. The code does not return a value directly or immediately. Instead, it returns a promise, which it will eventually provide later.

Promise in JavaScript is asynchronous, which means it takes time to resolve or complete. Just as searching an applicant's resume takes time to complete.

For this reason, the interviewer decided not to sit down and do nothing, so they began interviewing candidates based on their promise to deliver their resumes. We are replacing the promise of the actual resume with the returned resume.

The JS engine doesn't wait to do nothing either-it starts executing the rest of the code, waiting for the return value of promise.

The message text contains the status message for the resume search. For JavaScript Promise, this is also known as the return value.

If the news is "successful", we will continue to sign the candidate and grant him the post. If we fail, we will continue to reject his application.

For the JavaScript promise, we do this by using callback functions (promise handlers). These functions are defined in the nested then () method.

To specify the callback to call, use the following two functions:

Resolve (value): this indicates that the asynchronous task was successful. This calls the fulfillment callback in the then () handler.

Reject (error): this indicates an error while trying to run an asynchronous task. This invokes the reject callback in the then () handler.

If the promise succeeds, the fulfillment callback is called. If the promise is rejected, the rejected callback is invoked.

Promise is just a placeholder for an unfinished asynchronous task. When you define a promise object in a script, it does not immediately return a value, but a promise.

How to write Promise in JavaScript

You can define the promise in JavaScript by calling the Promise class and constructing such an object:

Const myPromise = new Promise ((resolve, reject) = > {setTimeout () = > {resolve ('this is the eventual value the promise will return');}, 300);}); console.log (myPromise)

Running it in the console returns a Promise object:

However, constructing an object is not the only way to define Promise. You can also use the built-in PromiseAPI to achieve the same functionality:

Const anotherPromise = Promise.resolve ("this is the eventual value the promise will return") console.log (anotherPromise)

Although the Promise in the first code example waits 3 seconds before using this is the eventual... The message implements Promise, but the Promise in the second code example will immediately implement it using the same message.

Reject promise in JavaScript

Promise can also be rejected. In most cases, rejections occur because JS encounters some kind of error while running asynchronous code. In this case, it calls the reject () function.

This is a simple and artificial example of how Promise is rejected:

Const myPromise = new Promise ((resolve, reject) = > {let a = false; setTimeout (() = > {return (a)? Resolve ('an is examples'): reject ('sorry, no a');}, 300);})

Can you think of the reason why this promise was rejected? If you say "because an is not fake", congratulations!

The promise in the third code example will resolve to reject after a three-second timeout because of the (a)? Statement is parsed to false, which triggers reject. Exe.

How to access previous Promise results in then ()

When Promise finally returns a value, you usually want to do something with that return value.

For example, if you are making a network request, you may want to access the value and display it on the user's page.

You can define two callback functions that you want to call when promise is implemented or rejected. These functions are defined in the nested then () method:

Const anotherPromise = new Promise ((resolve, reject) = > {setTimeout (() = > {resolve ('this is the eventual value the promise will return');}, 300);}); / / CONTINUATIONanotherPromise.then (value = > {console.log (value)})

Running this code displays a completion message in the console after three seconds:

Note that you can nest as many promise as you want. Each step is performed after the previous step, taking the return value of the previous step:

Const anotherPromise = new Promise ((resolve, reject) = > {setTimeout (() = > {resolve ('this is the eventual value the promise will return');}, 300);}); anotherPromise.then (fulfillFn, rejectFn) .then (fulfilFn, rejectFn) .then (value = > {console.log (value)})

But we missed something important.

Always keep in mind that a then () method must accept both an execution handler and a reject handler. In this way, if the Promise is satisfied, the first is called, and if the Promise is rejected because of an error, the second is called.

The promise in code examples 4 and 5 does not contain a second handler. Therefore, assuming that an error is encountered, there will be no reject handler to handle the error.

If you only want to define a callback function (aka completion handler) then () in, you will need catch () to nest a method at the bottom of the Promise chain to catch any possible errors.

How to use the catch () method in JS

Catch () calls this method whenever it encounters an error at any point in the commitment chain:

Const myPromise = new Promise ((resolve, reject) = > {let a = false; setTimeout (() = > {return (a)? Resolve ('an is kids'): reject ('sorry, no a');}, 300);}); myPromise.then (value = > {console.log (value)}) .catch (err = > {console.log (err)})

Because myPromise will eventually resolve to reject, the function then () defined in the nesting will be ignored. Instead, the error handler catch () will run and should log the following error message to the console:

This is the end of this article on "what is Promise in JavaScript?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report