注意then中的返回值
`then()**方法返回一个 [Promise`](https://developer.mozilla.org/zh-CN/docs/Web/API/Promise)。它最多需要有两个参数:Promise 的成功和失败情况的回调函数。
const promise1 = new Promise((resolve, reject) => {resolve('Success!');});promise1.then((value) => {console.log(value);// expected output: "Success!"});
注意:如果忽略针对某个状态的回调函数参数,或者提供非函数 (nonfunction) 参数,那么
then方法将会丢失关于该状态的回调函数信息,但是并不会产生错误。如果调用then的Promise的状态(fulfillment 或 rejection)发生改变,但是then中并没有关于这种状态的回调函数,那么then将创建一个没有经过回调函数处理的新Promise对象,这个新Promise只是简单地接受调用这个then的原Promise的终态作为它的终态。
语法
p.then(onFulfilled[, onRejected]);p.then(value => {// fulfillment}, reason => {// rejection});
参数
onFulfilled 可选
当 Promise 变成接受状态(fulfilled)时调用的函数。该函数有一个参数,即接受的最终结果(the fulfillment value)。如果该参数不是函数,则会在内部被替换为 (x) => x,即原样返回 promise 最终结果的函数
onRejected 可选
当 Promise 变成拒绝状态(rejected)时调用的函数。该函数有一个参数,即拒绝的原因(rejection reason)。 如果该参数不是函数,则会在内部被替换为一个 “Thrower” 函数 (it throws an error it received as argument)。
返回值
当一个 Promise 完成(fulfilled)或者失败(rejected)时,返回函数将被异步调用(由当前的线程循环来调度完成)。具体的返回值依据以下规则返回。如果 then 中的回调函数:
- 返回了一个值,那么
then返回的 Promise 将会成为接受状态,并且将返回的值作为接受状态的回调函数的参数值。 - 没有返回任何值,那么
then返回的 Promise 将会成为接受状态,并且该接受状态的回调函数的参数值为undefined。 - 抛出一个错误,那么
then返回的 Promise 将会成为拒绝状态,并且将抛出的错误作为拒绝状态的回调函数的参数值。 - 返回一个已经是接受状态的 Promise,那么
then返回的 Promise 也会成为接受状态,并且将那个 Promise 的接受状态的回调函数的参数值作为该被返回的Promise的接受状态回调函数的参数值。 - 返回一个已经是拒绝状态的 Promise,那么
then返回的 Promise 也会成为拒绝状态,并且将那个 Promise 的拒绝状态的回调函数的参数值作为该被返回的Promise的拒绝状态回调函数的参数值。 - 返回一个未定状态(
pending)的 Promise,那么then返回 Promise 的状态也是未定的,并且它的终态与那个 Promise 的终态相同;同时,它变为终态时调用的回调函数参数与那个 Promise 变为终态时的回调函数的参数是相同的。
// using a resolved promise, the 'then' block will be triggered instantly,// but its handlers will be triggered asynchronously as demonstrated by the console.logsconst resolvedProm = Promise.resolve(33);let thenProm = resolvedProm.then(value => {console.log("this gets called after the end of the main stack. the value received and returned is: " + value);return value;});// instantly logging the value of thenPromconsole.log(thenProm);// using setTimeout we can postpone the execution of a function to the moment the stack is emptysetTimeout(() => {console.log(thenProm);});// 上面的代码会依次返回:// Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}// "this gets called after the end of the main stack. the value received and returned is: 33"// Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: 33}
