promise 笔记
拒绝:
var promise=new Promise(function(resolve,reject){
throw new Error(0);
});
promise.then(function(arg){
console.log(arg);
}).catch(function(arg){
console.log('c' + arg);//走这
});
var promise=new Promise(function(resolve,reject){
reject(0);
});
promise.then(function(arg){
console.log(arg);
},function(arg){
console.log('j' + arg);//走这
}).catch(function(arg){
console.log('c' + arg);
异常:
var promise=new Promise(function(resolve,reject){
throw new Error(0);
});
promise.then(function(arg){
console.log(arg);
}).catch(function(arg){
console.log('c' + arg);//走这
});
var promise=new Promise(function(resolve,reject){
reject(0);
});
promise.then(function(arg){
console.log(arg);
},function(arg){
console.log('j' + arg);//走这
}).catch(function(arg){
console.log('c' + arg);
then() cath()会构建和返回一个promise实例:
var promise=new Promise(function(resolve,reject){
throw new Error('x');
});
promise.then(function(arg){
console.log(arg);
return 'xx';//返回给下一个then的resolve(抛异常也是下一个then的resolve)
},function(arg){
console.log('reject:' + arg);
return 'xx';//返回给下一个then的reject
}).catch(function(arg){
console.log('cathc' + arg);
})
.then(function(data){
console.log('last resolve:' + data);
},function(data){
console.log('last reject:' + data);
});
延迟,异步异常
var promise = new Promise(function(resolve, reject) {
setTimeout(function() {
reject('x');//可以捕获,如果是 throw 一个error就无法捕获
});
});
promise.then(function(arg) {
console.log('resole:' + arg);
}, function(arg) {
console.log('reject:' + arg);
})
.catch(function(arg) {
console.log('cathc:' + arg);
})
补充:
window.addEventListener("unhandledrejection", function (event) {
console.warn("WARNING: Unhandled promise rejection. Shame on you! Reason: "
+ event.reason);});
用来捕获拒绝,window.onerror只是捕获异常不会捕获promise的拒绝