es6 promise then对异常处理的方法

  1. then()里有两个回调函数,第一个是成功后(resolve返回)的回调function(data) {}, 另一个是失败后(reject返回)的回调function(err) {},异常发生时可以放在第二个回调里面处理。

  2. 也可以在then后面加.catch,在这里面进行异常处理

建议用2

function test(flag) {
return new Promise((resolve, reject) => {
if (flag == 1) {
resolve("success");
} else {
reject("fail");
}

})

}

function test2 () {
return new Promise((resolve, reject) => {
test(2).then((data) => {
console.log(data);
resolve(data);
}, (err) => {
console.log(err);
reject(err);
});
})

}

//错误写法
//function test2 () {
// return new Promise((resolve, reject) => {
// test(2).then((data, err) => {
// (data) => {
// console.log(data);
// resolve(data);
// }, (err) => {
// console.log(err);
// reject(err);
// }
// });
// });
//}

// 建议的写法
function test3 () {
return new Promise((resolve, reject) => {
test(2).then((data) => {
console.log(data);
resolve(data);
}).catch((err) => {
console.log(err);
reject(err);
});
});

}

test2().then((data) => {
console.log(data);
})

test3().then((data) => {
console.log(data);
})
阮一峰老师的es6教程里也有如下解释:

猜你喜欢

转载自www.cnblogs.com/dillonmei/p/12578621.html