Promise object features

  1. The status of an object is not affected. The Promise object represents an asynchronous operation with three states: Pending, fulfilled and Rejected. Only the result of an asynchronous operation can determine the current state, and no other operation can change the state.
  2. Once the state changes, it never changes again, and you can get this result at any time. There are only two possibilities for the state of the Promise object to change from pending to depressing and from pending to Rejected. As long as these two things are happening the state is fixed, it’s not going to change, it’s going to stay the same and that’s called resolved. If the change has already occurred, you can add a callback to the Promise object and get the same result immediately.

Promise shortcomings

  1. There is no way to cancel a promise, which executes immediately once it is created and cannot be cancelled halfway through.
  2. If the callback function is not set, errors thrown inside a promise are not reflected outside.
  3. When in the pending state, there is no way to know what stage of progress is currently being made.

A static method

  • Promise.reslove()
    1. Transform an existing object into a Promise object
    2. If the argument is a Promise instance, that instance is returned directly
    3. If the argument is a ThEnabled object (an object with a THEN method), it is first converted to a Promise object, and then the object’s THEN method is immediately executed
    4. If the parameter is a primitive value, a Promise object in the resolved state is returned and the primitive value is passed to the callback
    5. Return a Resolved Promise object with no arguments
  • Promise.reject()
    1. The return promise object is in the rejected state
  • Promise.all()
    1. Receives an array of Promise instances or an object with an Iterator interface
    2. Resolve becomes a Promise object if the element is not a Promise object
    3. If everything succeeds and the state becomes resolved, the returned values will be passed as an array to the callback
    4. Once there is a failure, the state changes to Rejected and the return value is passed directly to the callback
    5. The return value of all() is also the new Promise object
  • Promise.race()
    1. Whenever one of the first Promise instances to change (whether the state changes to Resolved or Rejected) triggers a callback in then, the return value is passed to the callback
    2. The return value of race() is also the new Promise object

Code usage and pitfalls

Common use

  1. The magic of Promise is that it allows us to use returns and throws inside callback functions
  2. If nothing is returned, undefined is returned by default
    loadAsync1()
    	.then(function(data1) {
    		return loadAsync2(data1)
    	})
    	.then(function(data2){
    	    return loadAsync3(data2)
    	})
    	.then(okFn, failFn)
    *******************	*****************
    loadAsync1()
    	.then(function(data1) {
    		loadAsync2(data1)
    	})
    	.then(function(data2){
    	    loadAsync3(data2)
    	})
    	.then(res= >console.log(res))	
    Copy the code

The catch () and then (null, fn)

In this case, the catch is not an ajaxLoad1 error but an ajaxLoad2 error. Js ajaxLoad1().then(res=>{return ajaxLoad2()}).catch(err=> console.log(err)) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / combine ajaxLoad1 (). Then (res = > {return ajaxLoad2 ()}, err=>console.log(err)) .catch(err=> console.log(err)) ```Copy the code

Through the Fall Through

If then or catch receives something other than a function, then penetration occurs, so you should ensure that the argument received by THEN is always a function

new Promise(resolve= >resolve(8))
 .then(1)
 .catch(null)
 .then(Promise.resolve(9))
 .then(res= > console.log(res))
/ / 8
Copy the code

Implement an Ajax operation with Promise

// 0 is not initialized. Open is not called
// 1. Open is invoked but send is not
// 2. Send a call to send() but no response
// 3. Receive Some response data has been received
// 4. Complete Complete the data response
 const ajax = function (params) {
      if(! params.url)return
      const promise = new Promise((resolve, reject) = > {
        const handler = function () {
          if (this.readyState ! = =4) return
          if (this.status == 200) {
            try {
              let resonse = JSON.parse(this.responseText)
              resolve(resonse)
            } catch (error) {
              reject(error)
            }
          } else {
            reject(new Error(this.statusText))
          }
        }
        const xhr = new XMLHttpRequest()
        if (params.method.toLowerCase() == 'get') {
          xhr.open('get', url + '? ' + formatParams(params.data));
          xhr.send()
        } else {
          xhr.open('post', url);
          xhr.send(JSON.stringify(params.data));
        }
        xhr.onreadystatechange = handler
        xhr.responseType = 'json'
        xhr.setRequestHeader('Accept'.'application/json');
      })
      return promise

      function formatParams(obj) {
        if(! data)return
        var arr = []
        for (let i in obj) {
          arr.push(`The ${encodeURIComponent(i)}=The ${encodeURIComponent(obj[i])}`)}return arr.join('&')}}Copy the code

Promise FAQs

A reject and a catch

This is a big pity, onRejected. Then (onFulfilled, onRejected) this is a big pity. -Promise. Then (onFulfilled). Catch (onRejected). Then the exceptions generated in the trap can be caught in. CatchCopy the code

If you throw an error in then without processing the error (catch), reject remains until the error is caught

Function taskA() {console.log(x); console.log("Task A"); } function taskB() { console.log("Task B"); } function onRejected(error) { console.log("Catch Error: A or B", error); } function finalTask() { console.log("Final Task"); } var promise = Promise.resolve(); Task A ". Then (taskB) //. Then does not catch A fault and does not print "Task B". Catch (onRejected) // Print error messages. Then (finalTask); Resolve -------output------- Catch Error: A or B,ReferenceError: x is not defined Final Task ' 'Copy the code

Each call to THEN returns a newly created Promise object, and inside the THEN is just the data returned

Var p1 = new promise (function (resolve) {resolve(100); var p1 = new promise (function (resolve) {resolve(100); }); p1.then(function (value) { return value * 2; }); p1.then(function (value) { return value * 2; }); p1.then(function (value) { console.log("finally: " + value); }); -------output------- finally: 100 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / method 2: Var p2 = new promise (function (resolve) {resolve(100); }); p2.then(function (value) { return value * 2; }).then(function (value) { return value * 2; }).then(function (value) { console.log("finally: " + value); }); -------output------- finally: 400 ```Copy the code

Throw an error in an asynchronous callback and you will not be caught

```JS // Errors thrown inside asynchronous functions will act like uncaught errors var promise = new Promise(function(resolve, reject) { setTimeout(function() { throw 'Uncaught Exception! '; }, 1000); }); promise.catch(function(e) { console.log(e); //This is never called }); ` ` `Copy the code