About the promise of a misunderstanding

Recently when writing code accidentally made a stupid mistake, with the request axios package http go request interface, after obtaining background data returned in then instance of an object request () method to get the local cache an object, in a case that the object is not to get value directly on the inside of the object to a value judgment, and at that time that the object must have value, but has been taking the catch () method, later, after examination revealed that the object is not to get the value, the problem is solved, but the hearts of a doubt.

When studying promise, you will see the words, the state of Promise, once changed, remains permanently in this state, it will not change the.

Yes, that doubts had entered the then () method why then () method inside error catch () Exception caught it there, that good Promise of state, once changed, remains permanently in this state, will not change of it?

Later looked again Ruan Yifeng teacher es6 standard entry, found to have been written very clearly.

thenThe method specified callback function, if the operation throws an error, will be catchcapture method.

So Promise of state, once changed, permanently maintain this state, will not change, what does it mean?

var p1  = new Promise((resolve,reject)=>{
    setTimeout(()=>{
      console.log('执行完成');
      reject(new Error('test'));
      resolve();
    })
  })
  p1.then((res)=>{
    console.log('then1')
  }).catch((err)=>{
    console.log('catch1')
  })

When executing the code above will output finished and catch1, that is, when the implementation of a reject, status changes, catch () method will catch the exception, then () method does not get to the value of the so-called promise of Once a state changes, this state is maintained permanently, will not be changed. I met with the appearance of wrong then () method to go, catch () method will catch exceptions are different issues.

 

Guess you like

Origin www.cnblogs.com/xiyangnanxia/p/11039081.html
Recommended