网站外包要注意什么,电子商城建设网站,做网站后端,桂林八桂网一般来说#xff0c;不要在then()方法里面定义 Reject 状态的回调函数#xff08;即then的第二个参数#xff09;#xff0c;总是使用catch方法。
// bad
promise.then(function(data) {// success}, function(err) {// error});// good
promise.then(function(data) { //…一般来说不要在then()方法里面定义 Reject 状态的回调函数即then的第二个参数总是使用catch方法。
// bad
promise.then(function(data) {// success}, function(err) {// error});// good
promise.then(function(data) { //cb// success}).catch(function(err) {// error});上面代码中第二种写法要好于第一种写法理由是第二种写法可以捕获前面then方法执行中的错误也更接近同步的写法try/catch。因此建议总是使用catch()方法而不使用then()方法的第二个参数。
跟传统的try/catch代码块不同的是如果没有使用catch()方法指定错误处理的回调函数Promise 对象抛出的错误不会传递到外层代码即不会有任何反应。
const someAsyncThing function() {return new Promise(function(resolve, reject) {// 下面一行会报错因为x没有声明resolve(x 2);});
};someAsyncThing().then(function() {console.log(everything is great);
});setTimeout(() { console.log(123) }, 2000);
// Uncaught (in promise) ReferenceError: x is not defined
// 123上面代码中someAsyncThing()函数产生的 Promise 对象内部有语法错误。浏览器运行到这一行会打印出错误提示ReferenceError: x is not defined但是不会退出进程、终止脚本执行2 秒之后还是会输出123。这就是说Promise 内部的错误不会影响到 Promise 外部的代码通俗的说法就是“Promise 会吃掉错误”。