Promise是干嘛用的呢?
Promise 对象用于表示一个异步操作的最终完成 (或失败)及其结果值。
函数嵌套与Promise
函数嵌套:
f1(a, b => {
f2(b, c => {
f3(c)
})
})
使用Promise:
f1(a)
.then(b => f2(b))
.then(c => f3(c))
f1(a)
.then(b => f2(b), onerror1)
.then(c => f3(c), onerror2)
.catch(err => {})
Promise的使用减少了缩进,并且方便了错误处理,解决了相对于异步回调的层层嵌套,代码可读性差的缺点。
一个 Promise 必然处于以下几种状态之一:
- 待定(pending): 初始状态,既没有被兑现,也没有被拒绝。
- 已兑现(fulfilled): 意味着操作成功完成。
- 已拒绝(rejected): 意味着操作失败。
Promise的链式调用:
promise.then()
.catch() //对错误进行统一处理,对于上述的onerror1,onerror2可以省去,这种做法更简单
.finally() //无论正确错误都会执行
Promise的基本使用:
function fn(arg) {
return new Promise(function(resolve, reject) {
if(true) {
resolve(data)
} else {
reject(reason)
}
})
}
fn(arg)
.then(function(data){
console.log(data)
}).catch(function(reason){
console.log(reason)
})
Promise是一个类(类是一个特殊的函数)
类方法:
- Promise.all //把全部resolve的结果放进一个数组
- Promise.race //得到一个最先resolve的结果
- Promise.reject //返回一个状态为失败的Promise对象,并将给定的失败信息传递给对应的处理方法
- Promise.resolve //返回一个状态由给定value决定的Promise对象。
手写一个简易的Promise
class Promise1 {
succeed = null
fail = null
state = 'pending'
resolve(result) {
setTimeout(() => {
this.state = 'fulfilled'
this.succeed(result)
})
}
reject(reason) {
setTimeout(() => {
this.state = 'rejected'
this.fail(reason)
})
}
constructor(fn) {
fn(this.resolve.bind(this), this.reject.bind(this))
}
then(succeed, fail) {
this.succeed = succeed
this.fail = fail
}
}
new Promise1((resolve, reject)=>{
setTimeout( () => {
if(Math.random() > 0.5){
resolve('succeed!你今天运气很棒哦!')
}else{
reject('fail!继续加油呀!')
}
},1000)
}).then(doIt => {
console.log(doIt)
},failReason => {
console.log(failReason)
})
参考自MDN Promise