Promise.prototype.catch() 方法是.then(null , rejection)的别名,用于指定发生错误时的回调函数。
错误处理的两种方法:
reject(“错误信息”).then(null ,messages =>{})
throw new Error('错误信息').catch(message =>{})(推荐使用这种,清晰好读,可以捕获亲年的错误信息。)
function getNumber() { var p = new Promise (function (resolve, reject) { setTimeout(function () { var num = Math.ceil(Math.random()*10); if (num <= 5){ resolve(num); } else { reject('大于五') } },2000) }) return p ; } //详细错解 // ReferenceError: somedata is not defined getNumber() .then(function (data) { console.log('resolve'); console.log(data); console.log(somedata) }) .catch(function (reason ,data) { console.log('reject') console.log(reason) });
在resolve的回调中,我们console.log(somedata);而somedata这个变量是没有被定义的。
如果我们不用Promise,代码运行到这里就直接在控制台报错了,不往下运行了,但是在Promise 里是传入带catch里去了,
也就是说进到catch方法里面去了,而且把错误原因传到了reason参数中。
即便是有错误的代码也不会报错了,这与我们的try/catch语句有相同的功能。
//throw catch const promise = new Promise(function(resolve, reject) { throw new Error('test'); }); promise.catch(function(error) { console.log(error); }); //reject const promise = new Promise(function(resolve, reject) { reject(new Error('test')); }); promise.catch(function(error) { console.log(error); });
通过上面两种写法,可以发现reject方法的作用等同于抛出出错误。
如果Promise状态已经变成resolved,在抛出错误是无效的。
const promise = new Promise(function(resolve, reject) { resolve('ok'); throw new Error('test'); }); promise .then(function(value) { console.log(value) }) .catch(function(error) { console.log(error) }); // ok
function getNumber() { var p = new Promise (function (resolve, reject) { setTimeout(function () { var num = Math.ceil(Math.random()*10); if (num <= 5){ resolve(num); } else { reject('大于五') } },2000) }) return p ; } getNumber().then(function(data) { console.log(name()); console.log('resolved'); console.log(data); }).catch(function(reason) { console.log('rejected'); console.log(reason); });
或
通过随机数 错误原因传到了reason参数中。即便是有错误的代码也不会报错了,这与我们的try/catch语句有相同的功能。