Promise.prototype.catch() - JavaScript Promise 对象
Promise.prototype.catch()
catch()方法返回一个Promise,并且处理拒绝的情况。它的行为与调用Promise.prototype.then(undefined, onRejected)
相同。(事实上, callingobj.catch(onRejected)
内部callsobj.then(undefined, onRejected)
).
语法
p.catch(onRejected); p.catch(function(reason) { // 拒绝 });
参数
onRejected当Promise 被rejected时,被调用的一个Function
。该函数拥有一个参数:reason
rejection 的原因。如果onRejected
抛出一个错误或返回一个本身失败的 Promise ,通过catch()
返回的Promise 被rejected;否则,它将显示为成功(resolved)。
返回值
一个Promise
.
描述
catch
方法可以用于您的promise组合中的错误处理。
Internally callsPromise.prototype.then
on the object upon which is called, passing the parametersundefined
and theonRejected
handler received; then returns the value of that call(which is aPromise
).
示例
使用链式语句的catch
方法
var p1 = new Promise(function(resolve, reject) { resolve('Success'); }); p1.then(function(value) { console.log(value); // "Success!" throw 'oh, no!'; }).catch(function(e) { console.log(e); // "oh, no!" }).then(function(){ console.log('after a catch the chain is restored'); }, function () { console.log('Not fired due to the catch'); }); // 以下行为与上述相同 p1.then(function(value) { console.log(value); // "Success!" return Promise.reject('oh, no!'); }).catch(function(e) { console.log(e); // "oh, no!" }).then(function(){ console.log('after a catch the chain is restored'); }, function () { console.log('Not fired due to the catch'); });
捕获抛出的错误
// 抛出一个错误,大多数时候将调用catch方法 var p1 = new Promise(function(resolve, reject) { throw 'Uh-oh!'; }); p1.catch(function(e) { console.log(e); // "Uh-oh!" }); // 在异步函数中抛出的错误不会被catch捕获到 var p2 = new Promise(function(resolve, reject) { setTimeout(function() { throw 'Uncaught Exception!'; }, 1000); }); p2.catch(function(e) { console.log(e); // 不会执行 }); // 在resolve()后面抛出的错误会被忽略 var p3 = new Promise(function(resolve, reject) { resolve(); throw 'Silenced Exception!'; }); p3.catch(function(e) { console.log(e); // 不会执行 });
如果已决议
//创建一个新的 Promise ,且已决议 var p1 = Promise.resolve("calling next"); var p2 = p1.catch(function (reason) { //这个方法永远不会调用 console.log("catch p1!"); console.log(reason); }); p2.then(function (value) { console.log("next promise's onFulfilled"); /* next promise's onFulfilled */ console.log(value); /* calling next */ }, function (reason) { console.log("next promise's onRejected"); console.log(reason); });
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)