Understanding Promise

Promise is simple to learn, memo

Promise synchronized with the wording solved the problem of asynchronous callback pyramid

Such as

getData1(data1 => {
  getData2(data1, data2 => {
    getData3(data2, data3 => {
      getData4(data3, data4 => {
        getData5(data4, data5 => {
          // 终于取到data5了
        })
      })
    })
  })
})

用Promise

getData1()
.then(getData2)
.then(getData3)
.then(getData4)
.then(getData5)
.then(data => {
  // 取到最终data了
})

Basic usage

P = the let new new Promise ((resolve, Reject) => {
   // do something 
  // then resolve under certain conditions, or Reject 
  IF ( / * Condition easily write _ ^ ^ * / ) { 
    resolve () 
  } the else { 
    Reject () 
  } 
}) 

p.then (() => {
     // if p is resolve the state, here proceeds 
}, () => {
     // if the Reject state is p 
})
  1. new Promise can promise an asynchronous process is converted into an object. With the promise to the object, and then have the promise programmatically.
  2. State .then used to promise an object registered callback function. It will return a promise object, calls can be chained, which is behind .then continue .then. Callback function registered in the state may be changed by the return statement .then promise of object returned state, and pass data to the callback registration status back .then; return statement may not be used, as the default promise is to resolve the returned objects .
  3. The callback function .catch for registration rejected state, but also the callback procedure error correction, that is, if the process of the previous program run error, will enter the implementation of the callback function. Like with .then will return to the promise of new objects.
  4. Promise.resolve call returns a status of the object promise fulfilled state, arguments are passed to the callback function later as the state data
  5. Promise.reject and Promise.resolve Similarly, except that the returned object's state is rejected promise

Analog traffic lights

componentDidMount(){
        function red(){
            console.log("red");
        }
        function yellow(){
            console.log("yellow");
        }
        function green(){
            console.log("green");
        }
        
        let light = (fn,timer) => new Promise(resolve=>{
            setTimeout(function(){
                fn();
                resolve();
            },timer)
        })
        function start(){
            Promise.resolve().then(()=>{
                light(red,3000)
            }).then(()=>{
                light(yellow,5000)
            }).then(()=>{
                light(green,8000)
            })
        }
        start();
        
        

    }

I wrote a test project in the react 

Recorded memo.

Guess you like

Origin www.cnblogs.com/junwu/p/11127571.html