拒絕:promise
var promise=new Promise(function(resolve,reject){異步
throw new Error(0);spa
});io
promise.then(function(arg){console
console.log(arg);event
}).catch(function(arg){ast
console.log('c' + arg);//走這function
});class
var promise=new Promise(function(resolve,reject){List
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的拒絕