官方文档定义:
一个 promise 必须提供一个 then 方法以访问其当前值、终值和据因。
promise 的 then 方法接受两个参数:
promise.then(onFulfilled, onRejected) Todo:这里只介绍onFulfilled,所以删除了关于onRejected的规范定义
onFulfilled 和 onRejected 都是可选参数。
如果 onFulfilled 不是函数,其必须被忽略
如果 onFulfilled 是函数:
当 promise 执行结束后其必须被调用,其第一个参数为 promise 的终值
在 promise 执行结束前其不可被调用
其调用次数不可超过一次
用通俗的话来说:
then方法提供一个自定义的回调函数,若传入非函数,则会忽略当前then方法。
回调函数中会把上一个then中返回的值当做参数值供当前then方法调用。
then方法执行完毕后需要返回一个新的值给下一个then调用(没有返回值默认使用undefined)
每个then只可能使用前一个then的返回值
举个例子,先看一下4个primise到底有什么区别?
let func = function() {
return new Promise((resolve, reject) => {
resolve('返回值');
});
};
let cb = function() {
return '新的值';
}
func().then(function () {
return cb();
}).then(resp => {
console.warn(resp);
console.warn('1 =========<');
});
func().then(function () {
cb();
}).then(resp => {
console.warn(resp);
console.warn('2 =========<');
});
func().then(cb()).then(resp => {
console.warn(resp);
console.warn('3 =========<');
});
func().then(cb).then(resp => {
console.warn(resp);
console.warn('4 =========<');
});
结果
我们带着三个疑问来回答问题:
1,上一个then中传入了回到函数吗?
2,上一个then提供了返回值吗?
3,上一个then若提供了返回值,返回了什么?
分析解释:
执行第一个方法:
func().then(function () {
return cb();
}).then(resp => {
console.warn(resp);
console.warn('1 =========<');
});
返回结果: 新的值
1 =========<
因为传入了回调函数,而且回调函数中把cb执行后的返回值当做then中的返回值,所以输出了"新的值"
执行第二个方法:
func().then(function () {
cb();
}).then(resp => {
console.warn(resp);
console.warn('2 =========<');
});
返回结果: undefined
2 =========<
因为虽然传入了回调方法,只是执行了cb方法,并没有return值,定义中讲过若没有返回值,提供下一个then使用的参数就是undefined,所以打印出来就是undefined
执行第三个方法:
func().then(cb()).then(resp => {
console.warn(resp);
console.warn('3 =========<');
});
返回结果: 返回值
3 =========<
因为then中cb()执行后返回的并不是一个函数,在Promise规范中会自动忽略调当前then,所以会把func中的返回值供下一个then使用,输出了“返回值”
执行第四个方法:
func().then(cb).then(resp => {
console.warn(resp);
console.warn('4 =========<');
});
返回结果: 新的值
4 =========<
因为第一个方法在回调内部返回cb执行后的值,第四个方法则直接把cb当做回调,第一个方法与第四个方法异曲同工之妙,所以也输出了“新的值”。
原文地址:
https://segmentfault.com/a/1190000010420744?utm_source=tag-newest