In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to get started on the basis of Promise objects, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.
Let's learn about Promise today. In fact, this is also a test site in the written test.
Basic introduction
The Promise object is the specification put forward by the CommonJS working group. Promise was originally only an idea put forward by the community. Some external function libraries first implemented this function, and it was written into the language standard in ES6.
Objective: to provide a unified interface for asynchronous operation
What Promise is, it is an object in a javascript that acts as a proxy and acts as an intermediary between asynchronous operations and callback functions.
Avoid something similar to
The generation of this nested hell. To make our code easier to read and use Promise, everyone said yes
(new Promise (F1). Then (f2))
Conclusion: Promise makes the downward development of asynchronous operation into horizontal development, and the program flow becomes clear and easy to read.
Basic thought
The asynchronous task returns a Promise object that has three states
1.pending (not completed)
2. Completed (completed)
3.rejected (failed)
It can be changed in two ways.
1.pending-- > resolved/fulfilled
2.pending-- > rejected
It has two results.
1. The asynchronous operation succeeds. A value is returned and the status changes to resolved.
two。 The asynchronous operation failed, an error was thrown and the status changed to rejected
Promise uses the .then () method to add callback functions, and then receives two callback functions, * * for success and one for failure. The main purpose is to call the relative callback function when the state changes.
And then can be called chained.
Basic use
The Promise constructor takes a function as an argument, and the two parameters of the function are resolve and reject. They are provided by the JS engine and do not need to be deployed yourself.
Promise (function (resolve,reject) {})
The function of resolve is to change the Promise object from unfinished to successful (Pending- > Resolved), call it when the asynchronous operation is successful, and pass the result of the asynchronous operation as a parameter.
The function of reject is to change the Promise object from never completion to failure (Pending- > Rejected), call it when the asynchronous operation fails, and pass the error reported by the asynchronous operation as a parameter.
The Promise.then () method can be used to specify callback functions for Resolved state and Reject state.
Promise.then (function (value) {/ / success + _ +!}, function (value) {/ / failed QQ})
We only want to use promise.then (undefined, onRejected) or promise.catch (onRejected) when handling exceptions.
! Be careful! There is a pit here, which will be explained in the in-depth festival.
The Promise.all () method takes an array of promise objects as parameters, and the .then method is called when all Promise objects in the array become resolve/reject, where the incoming promise starts at the same time and executes in parallel.
Promise.all ([promise1,promise2,.])
The Promise.race () method takes an array of promise objects as parameters as the Promise.all () method, but when a promise object in the array enters the fulfilled or rejected state, subsequent processing begins.
Promise.race ([promise1,promise2,.])
Related grammatical sugar
Promise.resolve (42); / / equivalent to new Promise (function (resolve) {resolve (42);}); Promise.reject (new Error ("error")); / / equivalent to new Promise (function (resolve,reject) {reject ("error");})
In-depth
About Thenable object
This is very similar to Promise, with .then methods.
A classic example is that the value returned by jQuery.ajax () is thenable.
Var promise = Promise.resolve ($.ajax ('/ json/comment.json'))
In this way, you can convert thenable objects to promise objects
Portal: Promise.resolve ()
About promise design: always operate asynchronously
You can see what's wrong with this place by looking at the code.
Var promise = new Promise (function (resolve) {console.log ("inner promise"); / / 1 resolve (42);}); promise.then (function (value) {console.log (value); / / 3}); console.log ("outer promise"); / / 2 / / the result is / * inner promise / / 1 outer promise / / 2 42 / / 3 * /
As you can see, even if the promise object has determined the state when we call Promise. Thread, Promise will call the callback function asynchronously, which is the policy of the design of the callback.
About calling then/catch
Each time then/catch is called, a promise object is returned. At this point, we can tell that each promise object is actually different by using =.
Differences in error handling between then and catch
This is easy to understand in combination with the previous point.
Directly above, from JavaScript Promise Mini Book (Chinese version)
In combination with our code.
/ / onRejected will not be called function badMain (onRejected) {return Promise.resolve (42). Then (throwError, onRejected);} / / onRejected will be called function goodMain (onRejected) {return Promise.resolve (42). Then (throwError) .catch (onRejected);}
Errors in onFullfilled, such as errors in throwError, will not cause onRejected execution (catch exceptions). We can only catch them through the following catch methods.
Basic application
Incompatibility aspect
If it is not compatible, use polyfill.
With regard to IE8 and the following versions, catch will cause identifier not found errors due to reserved words in ES3, for which we can use ["catch"] or then (undefined,function () {}) to catch, while in some class libraries, caught is used as the function name to avoid this problem. It is worth noting that many compression tools come with .catch transfer ["catch"]
Application example:
Load Picture
Var preloadImage = function (path) {return new Promise (function (resolve,reject) {var image = new Image (); image.onload = resolve; image.onerror = reject; image.src = path;})} preloadImage ("https://dn-anything-about-doc.qbox.me/teacher/QianDuan.png").then(function(){ alert (" picture loaded successfully ");}, function () {alert (" picture load failed ");})
Ajax operation
Function search (term) {var url = 'http://example.com/search?q=' + term; var xhr = new XMLHttpRequest (); var result; var p = new Promise (function (resolve, reject) {xhr.open (' GET', url, true); xhr.onload = function (e) {if (this.status = this.responseText) Resolve (result);}}; xhr.onerror = function (e) {reject (e);}; xhr.send ();}); return p;} search ("Hello World"). Then (console.log, console.error)
Back to the beginning, in fact, the advantage of Promise object lies in the standard chain call, you can clearly see the program flow. And a unified method of handling errors can be defined.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
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.