×

学习下Promise中then的链式回调

作者:天空2019.01.28来源:Web前端之家浏览:12819评论:0
关键词:promise回调函数

学习下Promise中then的链式回调,首先来看个DEMO。

new Promise((resolve, reject) => {
            reject(1); // 确定promise状态为rejected
        }).then((fullfilled) => {
            console.log(fullfilled);
        }, (rejected) => {
            console.log(rejected, '2-1'); // 执行这里,then方法必须返回一个新的Promise实例,这个没有明式 return 值,便隐式触发新promise的fullfilled状态,进入下一个then的fullfilled回调
        }).then((fullfilled) => {
            console.log(fullfilled, '3-1'); // 执行这里,因上一步resolve未传值,所以fullfilled为undefined,继续隐式触发fullfilled回调
        }, (rejected) => {
            console.log(rejected, '3-2');
        }).then((fullfilled) => {
            console.log(fullfilled, '4-1'); // 执行这里
            return Promise.reject(5); // 明式返回rejected的promise
        }, (rejected) => {
            console.log(rejected, '5-1');
        }).catch((error) => {
            console.log(error, '6-1'); // 执行这里,被catch捕获,error为上一步reject传入的值。因Promise.prototype.catch方法是.then(null, rejection)或.then(undefined, rejection)的别名,用于指定发生错误时的回调函数,所以catch同样返回一个新的promise,若没有显示指定,便同上执行隐式操作
        }).then(fullfilled => {
            console.log(fullfilled, '7-1'); // 执行这里
        }, rejected => {
            console.log(rejected, '7-2');
        })

运行结果如下:

1 "2-1"
undefined "3-1"
undefined "4-1"
5 "6-1"
undefined "7-1"

总结:

Promise.prototype.then()返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。因此可以采用链式写法,即then方法后面再调用另一个then方法。

then方法中若有显式 return 一个新的 promise(包括fullfilled和rejected)则显示执行。若无显式指定,则隐式触发新promise的pending->fullfilled状态变更,进入下一个then的fullfilled回调。

因Promise.prototype.catch()方法是.then(null, rejection)或.then(undefined, rejection)的别名,用于指定发生错误时的回调函数,所以catch同样返回一个新的promise,若没有显示指定,便执行隐式操作。

建议:

不要在then方法里面定义 Reject 状态的回调函数(即then的第二个参数),总是使用catch方法。

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/jscnv258305k.html

网友评论文明上网理性发言 已有0人参与

发表评论: