zjbc / blog Goto Github PK
View Code? Open in Web Editor NEWblog
blog
function start () {
return new Promise(function(resolve, reject){
resolve('start')
})
}
start()
.then(function(data){
console.log("第一个",data)
return Promise.resolve("p1")
})
.then(function(data){
console.log("第二个",data)
return Promise.reject("p2")
})
.then(function(data){
console.log("第三个",data)
return Promise.resolve("p3")
})
.catch(function(err){
console.log("第四个", err)
return Promise.resolve("p4")
})
.then(function(data){
console.log("第五个",data)
return Promise.resolve("p5")
})
可以看到catch是捕获到之前promise reject的参数
一旦promise改变了状态变成rejected 就跳过了后面的promise
catch 也可以返回一个新的promise
可以看到只要前面有promise的reject 改变了promise的状态 就会跳过后面的then方法直接到catch里面
所以在promise链式调用时候 要有不想在某个then以后不再调用了其他的 就可以当做一个异常来处理
返回一个异常信息给 catch 通过返回来判断是程序出现异常还是中止导致
如果在promise then 的链路中也对错误进行了捕获就是不一样的效果了
Promise.resolve()
.then(function(){
console.log('第一个')
throw 'throw 1' // 抛出一个错误
})
.then(function(){
console.log('第二个')
}, function(err){
console.log('捕获第一个错误')
})
.then(function(){
console.log('第三个')
})
.catch(err => {
console.log("catch", 错误)
})
以上结果
第一个
捕获第一个错误
第三个
这样就不能中止后面的then了
利用then第二个参数 来改变promise 的状态
Promise.resolve()
.then(function(){
console.log('第一个')
return new Promise(function(resolve, reject){}) // 这里返回个是pending状态的promise
})
.then(function(){
console.log('第二个')
}, function(err){
console.log('捕获第一个错误')
})
.then(function(){
console.log('第三个')
})
.catch(err => {
console.log("catch", 错误)
})
结果
第一个
返回一个新的pending状态的promise 原来的promise对象跟现在的返回的promise对象状态一样 就中止了 之前promise链
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.