Promise.then

时间:2022-12-24 17:44:56

Promise.then

1、If onFulfilled returns a promise, the return value of then will be resolved/rejected by the promise.

  如果then的handler中返回一个promise(叫A),那么then()所返回的promise(叫B)的值,将会是这A的值。

function resolveLater(resolve, reject) {
setTimeout(function () {
resolve(10);
}, 1000);
}
function rejectLater(resolve, reject) {
setTimeout(function () {
reject(20);
}, 1000);
} var p1 = Promise.resolve('foo');
var p2 = p1.then(function() {
// Return promise here, that will be resolved to 10 after 1 second
return new Promise(resolveLater);
});
p2.then(function(v) {
console.log('resolved', v); // "resolved", 10
}, function(e) {
// not called
console.log('rejected', e);
}); var p3 = p1.then(function() {
// Return promise here, that will be rejected with 20 after 1 second
return new Promise(rejectLater);
});
p3.then(function(v) {
// not called
console.log('resolved', v);
}, function(e) {
console.log('rejected', e); // "rejected", 20
});

2、In practice, it is often desirable to catch rejected promises rather than use then's two case syntax, as demonstrated below.

  通过使用catch()来处理失败,而不是使用then()的第二个参数。

Promise.resolve()
.then( () => {
// Makes .then() return a rejected promise
throw 'Oh no!';
})
.catch( reason => {
console.error( 'onRejected function called: ', reason );
})
.then( () => {
console.log( "I am always called even if the prior then's promise rejects" );
});

3、catch()中如无异常,则返回的是一个resolved promise。

Promise.reject()
.then( () => 99, () => 42 ) // onRejected returns 42 which is wrapped in a resolving Promise
.then( solution => console.log( 'Resolved with ' + solution ) ); // Resolved with 42

4、通过throw或rejected Promise来返回一个异常。

Promise.resolve()
.then( () => {
// Makes .then() return a rejected promise
throw 'Oh no!';
})
.then( () => {
console.log( 'Not called.' );
}, reason => {
console.error( 'onRejected function called: ', reason );
});

5、当return一个value时,实际上返回的是 Promise.resolve(<value>)

var p2 = new Promise(function(resolve, reject) {
resolve(1);
}); p2.then(function(value) {
console.log(value); //
return value + 1;
}).then(function(value) {
console.log(value + '- This synchronous usage is virtually pointless'); // 2- This synchronous usage is virtually pointless
}); p2.then(function(value) {
console.log(value); //
});

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then