So without further ado, what is promise? Promise is a constructor and that’s what it is.
Example code:
var promise = new Promise(function(resolve,reject){
// … some code
Resolve (value); resolve(value); }
else{ reject(error); }});
The Promise constructor takes a function as an argument, resolve and reject. They are two functions provided by the JavaScript engine, not deployed by itself.
The resolve function changes the state of the Promise object from “unfinished” to “successful” (from Pending to Resolved), calls it when the asynchronous operation succeeds, and passes the result of the asynchronous operation as an argument. The reject function is called when an asynchronous operation fails and passes any errors reported by the asynchronous operation as arguments.
After the Promise instance is generated, we can use the THEN method to specify the Resolved and Rejected state callback functions:
promise.then(function(value){
// sucess
},function(error){ // failure }); 12345Copy the code
The then method can take two callback functions as arguments. The second function is optional and does not have to be provided. Both of these functions accept as arguments a value passed from the Promise object.
Conclusion: The advent of promises is a good way to handle callback hell, allowing us to write asynchronous code in a synchronous code style and place time-consuming operations within promises for logical processing. Resolve. Reject processes success and failure. And then finally we can write a catch pocket.
I just changed my city and interviewed for a job. In fact, I wanted to write a technical blog for a long time and never did.
Write for the first time there must be deficiencies, and then slowly improve and optimize. Write anything to record your recent study.