This article mainly introduces examples of the return values of then and catch in ES6 Promise. It has certain reference value. Now I share it with you. Friends in need can refer to it.
Sothen method and catch method will both return a Promise object
(Yes, even if return is a certain value, or throw error, or no value is returned)
Let's take a look at the definition of MDN. It may be a bit messy for the sake of rigor. undefined, also the return value)
,throw error
return Promise2. Let’s talk about the return value and throw error.
1. Return value situation:
. See the example of the code
The output result is as follows:var example = new Promise((fulfill, reject)=>{ let i = 1; fulfill(i); }) example .then((value)=>{ console.log(value); value++; return value; }) .then((value) => {console.log(value); });
Back to the above question, if
does not return, then undefined
var example = new Promise((fulfill, reject)=>{ let i = 1; fulfill(i); }) example .then((value)=>{ console.log(value); value++; }) .then((value) => {console.log(value);});
Return The Promise will becomeRejected
in the catch orthen’s second callback function parameter
Something that has been confused before appears here.
Repeat this sentence again:catch is syntactic sugar for then, which is an alias of then(null, rejection).
So, assuming that the
return value in the catch is, the new Promise object will also be in the accepting state.
Look at the example:
var example = new Promise((fulfill, reject)=>{ let i = 1; reject(i); }) example .catch(()=>{console.log('我是第一个catch的回调函数'); return 1;}) .then(() =>{console.log('我是第一个then的回调函数'); throw Error }) .catch(()=>{console.log('我是第二个catch的回调函数')}) .then(() => {console.log('我是第二个then的回调函数')})
executes the first catch The callback function
The callback function of the first catch
, soExecute the callback function of the first then
The callback function of the first thenthrow Error
, soExecute the callback function of the second catch
The callback function of the second catchruturn undefined (as mentioned above)
, soExecute the callback function of the second then
3. Return Promise case
As for the case of return Promise, the same is true. I have just started to contact Promise. I feel uncomfortable with the syntax: Promise objects are automatically generated for you? ! Later, after reading part of the source code analysis, I roughly understood why it was like this. I will also put the link below.
Related recommendations:
Introduction to ES6 Class inheritance and super
##jQuery-Ajax requests Json data and loads it on the front-end pageThe above is the detailed content of Examples of return values of then and catch in ES6 Promise. For more information, please follow other related articles on the PHP Chinese website!