通过reject传异常:
控制台输出:
b函数
index.html:19 reject打印Error对象 Error: throw error
at index.html:9:24
at new Promise (
at index.html:4:29
通过throw抛异常:
控制台输出:
b函数
index.html:19 打印Error对象 Error: throw error
at index.html:10:23
at new Promise (
at index.html:4:29
所以有这样的等价关系:
p.then((val) => console.log('fulfilled:', val)).catch((err) => console.log('rejected', err));// 等同于
p.then((val) => console.log('fulfilled:', val)).then(null, (err) => console.log("rejected:", err));
第一个then()
方法指定的回调函数,如果运行中抛出错误,也会被catch()
方法 或第二个then()
方法指定的第二个回调函数 捕获。
ES6 入门教程
复习知识点:
const promise = new Promise(function(resolve, reject){})中的resolve和reject是函数指针形参,定义Promise时,还不知道resolve和reject具体是什么函数。只有执行到promise.then(a,b),才会把a函数和b函数的指针赋给new Promise中定义的resolve和reject。
resolve("value")会将字符串"value"作为参数传给a()函数,可以理解为好像是将resolve("value")替换成a("value"),resolve()像是个占位符,将来会被then()的第一个参数传入的函数(本例为a() )替换。
async await
ES6 入门教程