When I was a kid, I looked through a lot of documentation about Promise, and I didn’t really understand what it meant to address the pain points of asynchronous operations until I looked through all the Chinese documents on The first page of Google, and I had an Epiphany, which is actually the simplest literal translation in English — it’s a Promise, Equivalent to in the code to provide a commitment at any time later, to do what the promise may cash may also be unable to meet, of course, may be in the process of cash Use this to replace once we need to write a callback function, can avoid the JavaScript callback hell in the program So the first not to learn grammar, From another way to understand first, I hope to help you better study or use the Promise

What is a Promise?

Promises are a solution for asynchronous programming that can replace traditional solutions such as callback functions and events. ES6 has unified usage and provides native Promise objects that represent the final completion (or failure) of an asynchronous operation and its resulting value. Promise has the following two features:

  1. The status of an object is not affected
    • Only the result of an asynchronous operation can determine which state it is in, and no other operation can change that statePromiseThe origin of the name, it means promise in English, means that no other means can change
  2. Once a state changes, it never changes, which means that a Promise can only have one state at any one time
    • Pending: Initial state, not success or failure state; This is a pity (resolved) : the operation is completed successfully. Rejected: Indicates that the operation fails

    • The state of the Promise object can change in only two ways: As soon as you change from Pending to Resolved and from Pending to Rejected, the state is frozen and will remain unchanged. Even if the change has already happened, you can add a callback function to the Promise object and get the result immediately. This is quite different from an Event, which has the characteristic that if you miss it and listen again, you will not get the result

The creation and use of promises

  1. The constructor accepts a name namedexecutorThe executing function takes twoF functionParameters,resolveandreject.
new Promise( /* executor */ function(resolve, reject { ... }));Copy the code
  1. Promises are typically used to block code and asynchronous operations, including file calls, API calls, DB calls, IO calls, and so on
  2. The start of these asynchronous operations occurs in the execution function and, if the asynchronous operation succeeds, passespromiseCreator call ofresolve()The function returns the expected result, and again, if an unexpected error occurs, by callingreject()The function passes error details
  3. Due to thepromiseIt will be executed immediately. We can’t check itpromiseSo create one that takes time to executepromiseThe easiest way to do this is to usesetTimeOut()Function, through the output of the browser console, you can see the state mentioned above and how it changes
Var promiseFir = new Promise(function(resolve, reject) {setTimeout(function() {resolve({message: ', code: 200 }); }, 2000) }) console.log(promiseFir); setTimeout(function() { console.log(promiseFir); }, 2000).Copy the code

The method of Promise

  1. Three prototyping methods
    • Prototype. Then (onFulfilled, onRejected) chain operation
    • Prototype. Catch (onRejected) Catch an error
    • Promise. Prototype. Finally (onFinally) in the end
    • Here’s a quick and simple example of how to use these three prototype methods
// To take a short story as an example, you are a school child and you ask your mother for a phone number. = new Promise(function(resolve, reject) {momsSavings = 20000; // momsSavings = 200000; PriceOfPhone = 60000; priceOfPhone = 60000; priceOfPhone = 60000; if (momsSavings > priceOfPhone) { resolve({ brand: "iphone", model: "6s" }); "We don't have enough savings. Let's save more." ); }}); Momspromise.then (function(value) {console.log(" Wow, I got this phone as a gift ", json.stringify (value)); }); Momspromise. catch(function(reason) {console.log(" Mom can't buy me a phone, because ", reason); }); Momspromise.finally (function() {console.log(" I still love my mom whether she can buy me a phone or not "); });Copy the code
  1. Four static methods
    • Promise.resolve()
    • Promise.reject()
    • Promise.all()
    • Promise.race()

Prototype. Then (onFulfilled, onRejected) chain operation

  1. Promise.prototype.then()Method returns a new onePromise object, so we can use the chain notation
  2. Promise.prototype.then()The method takes the following three parameters: a success callback, a failure callback, and a forward callback. In general, only the first callback needs to be implemented, and the rest is optional
Function ptFir() {return new Promise(function(resolve, reject) {setTimeout(function() {console.log(' console.log '); Resolve (' method 1 completes execution '); }, 2000) }) } function ptSec() { return new Promise(function(resolve, Reject) {setTimeout(function() {console.log(' method 2 execute '); Resolve (' method 2 completes '); }, 1000) }) } function ptThi() { return new Promise(function(resolve, Reject) {setTimeout(function() {console.log(' method 3 execute '); Resolve (' method 3 completes '); }, 3000)})} ptFir().then(function(data) {console.log(' first callback: '+ data); return ptSec(); }). Then (function(data) {console.log(' second callback: '+ data); return ptThi(); }). Then (function(data) {console.log(' third callback: '+ data); Return 'not done yet? It must be over! '; }).then(function(data) { console.log(data); })Copy the code

Prototype. Catch (onRejected) Catch an error

  1. Promise.prototype.catch()Method isPromise.prototype.then(null, rejection)Alias to specify the callback function in case of an error
  2. Promise objectErrors are “bubbling” and are passed backward until they are caught, that is, they are always passed on to the next errorcatchStatements capture
Promise ().then(function(data) {// todo something}).catch(function(err) {// todo something})Copy the code

Promise. Prototype. Finally (onFinally) in the end

Regardless of the final state of the Promise object, the callback specified by the finally method is executed after the callback specified by. Then or catch is executed

Promise ().then(function(data) {// todo something}).catch(function(err) {// Todo something}).finally(function(result) { // Then /catch must be done after})Copy the code

Promise.resolve() / Promise.reject()

  1. These two are help methods or shortcuts that help you create easilyresolveandrejectmethods
  2. Note that: ifPromise.resolve()Method parameters that do not have.then()The object of a method (also calledThenable object), returns a new onePromise objectAnd its state isfulfilled; ifPromise.resolveThe argument to the method is onePromise objectIs returned intact
  3. Promise.reject()Method as above
Var promise = promise. resolve('Hello! '); // var promise = promise. reject(' error, here is the error found! '); Then (function(data) {console.log(data)}); promise.catch(function(err) { console.log(err) });Copy the code

Promise.all()

  1. When you deal with multiplepromiseIt is best to create one firstPromise arrayAnd then for thesePromise setsPerform the necessary operations
  2. Promise. All (iterable) methodReturns aPromise instance, this instance inIterable parametersIn all thepromise
  3. Resolved or not included in parameterspromiseWhen the callback completes (resolve)
  4. If the parameterpromiseThere is a callback rejected (Reject), and this instance fails (Reject) for the first reasonFailure to promiseThe results of the
  5. * * * attention!!!!!! *** The asynchronous operations are executed in parallel and will not be entered until they are all executedthen()Inside, andall()The method puts the results of all asynchronous operations into an arraythen()
  6. The following example needs to be explained
    • There are only three methods where all the states becomefulfilledThe state of P will change tofulfilled, the return values of the three methods form an array, which is passed to p’s callback function
    • As long as one of the three methods isrejectedThe state of p becomesrejectedAt this time, the first to berejectThe return value of the instance of p is passed to p’s callback function
Function ptFir() {return new Promise(function(resolve, reject) {setTimeout(function() {console.log(' console.log '); Resolve (' method 1 completes execution '); }, 2000) }) } function ptSec() { return new Promise(function(resolve, Reject) {setTimeout(function() {console.log(' method 2 execute '); Resolve (' method 2 completes '); }, 1000) }) } function ptThi() { return new Promise(function(resolve, Reject) {setTimeout(function() {console.log(' method 3 execute '); Resolve (' method 3 completes '); }, 3000) }) } Promise.all([ptFir(), ptSec(), ptThi()]).then(function(data) { console.log(data); console.log({}.toString.call(data)); })Copy the code

Promise.race()

  1. Promise.race(iterable)Method returns apromise, once one of the iteratorspromiseResolved or rejected, returnedpromiseIt will be resolved or rejected
  2. all()The effect of this method is to execute the callback based on the slowest runner **, so there is another method ** to execute the callback based on the fastest runner **, which israce()Method, the word originally means race
  3. thisrace()What’s the use of methods? There are a lot of scenarios that we can userace()Set a timeout for an asynchronous request and perform the action after the timeout
All ([ptFir(), ptSec(), ptThi()]). Then (function(data) {console.log(data); console.log({}.toString.call(data)); })Copy the code

Use some of Promise’s rules of thumb

  1. Use Promise for asynchronous operations or blocking code

  2. For readability, resolve() and then(), reject() correspond to.catch()

  3. Be sure to write both the.catch() and.then() methods to fulfill all promises

  4. If something needs to be done in either case, use.finally()

  5. We only change each promise once

  6. We can add multiple handlers to a promise

  7. The return types of all methods in a Promise object, whether static or prototypical, are Promises

  8. In the all() method, the order of the promises remains in the value variable regardless of which promise is not completed first

———— for a thorough understanding of promises in Javascript. ———— for a simple understanding of then. ———— for understanding promises in Javascript JavaScript object of Promise

I’m FX67ll.com. If you find anything wrong with this article, please comment on it in the comments section. Thank you for reading! If you like this article, welcome to visit my github warehouse address, for me to click a Star, Thanks~ 🙂 forward please note the reference article address, very thank you!!