我们知道Promise对象具有then,catch等方法,在执行这些方法之后,也会返回一个Promise对象,正因为如此,Promise对象才有链式写法。规则如下:
对于then方法,1.如果then方法里面的回调函数没有返回值,并且也没有抛出错误,那么该then方法返回的Promise对象的状态为fulfilled,其value为undefined;
var p = new Promise(function (resolve, reject) {
resolve(555);
});
p.then(function (value) {
console.log(value);
}).then(function (res) {
console.log(res);
console.log(666);
});
打印结果如下:
2.如果回调函数抛出了错误,那么该then方法返回的Promise对象的状态为rejected,value为抛出的错误值。
var p = new Promise(function (resolve, reject) {
resolve(555);
});
p.then(function () {
throw "abc";
}).catch(function (res) {
console.log(res);
});
打印结果如下: