Promise干嘛用
一個異步解決方案
例如 多個setTimeout()嵌套造成回調(diào)地獄
setTimeout(function() {
// do something..
setTimeout(function() {
// do something..
}, 1000)
}, 1000)
可以用Promise解決
new Promise(function(resolve, reject){
setTimeout(function() {
// do something..
resolve(res)
}, 1000)
}).then(res => {
setTimeout(function() {
// do something..
return res
}, 1000)
}).then(res => {
setTimeout(function() {
// do something..
return res
}, 1000)
}).catch(err => {
console.log(err)
})
Promise怎么用?
new Promise(function(resolve, reject){
resolve(res) // 進(jìn)入.then()
reject(res) // 進(jìn)入.catch()
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
Promise特點
- Promise狀態(tài)(PromiseStatus)一旦改變吏够,不可逆箕憾,不可再更改
new Promise(function(resolve, reject){
resolve(res) // 只能進(jìn)入.then()
reject(res) // 不會進(jìn)入.catch
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
- Promise的then方法參數(shù)期望收到一個函數(shù)福扬,如果傳入非函數(shù)脯倒,則發(fā)生值穿透
new Promise(function(resolve, reject){
resolve('123')
}).then('res').then(res => {
console.log(res) // 打印出‘123’ 值穿透到下一個then里面
})
new Promise(function(resolve, reject){
resolve('123')
}).then('res').catch(res => {
console.log(res) // 值不會穿透進(jìn)入catch
})
- Promise回調(diào)是同步的愿吹,then的回調(diào)是異步的
new Promise(function(resolve, reject){
console.log(1)
resolve('123')
}).then(res => {
console.log(2)
console.log(res)
return(`${res}4`)
}).then(res => {
console.log(3)
console.log(res)
})
console.log(4)
==結(jié)果==
1
4
2
123
3
1234
- Promise鏈?zhǔn)秸{(diào)用.then() 如果有return的話 返回的是一個promise對象金踪,如果不return 則下一個then接不到參數(shù)浊洞;如果==拋出異常==則返回一個reject狀態(tài)的Promise,進(jìn)入catch.上一個then的返回值是下一個then接收到的參數(shù)胡岔。
new Promise(function(resolve, reject){
resolve('123')
}).then(res => {
console.log(res)
throw new Error('this is an error')
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err) // 進(jìn)入catch 在此打印 this is an error
})
==必須拋出異常throw error法希,如果return的話就進(jìn)入下一個then了==
new Promise(function(resolve, reject){
resolve('123')
}).then(res => {
console.log(res)
return new Error('this is an error')
}).then(res => {
console.log(res) // 進(jìn)入then 在此打印 this is an error
}).catch(err => {
console.log(err)
})
- then的回調(diào)里return一個Promise會進(jìn)入等待狀態(tài),直到return的Promise改變
new Promise(function(resolve, reject){
resolve('123')
}).then(res => {
return new Promise(function(resolve, reject) {
setTimeout(function(){
resolve('456') // 3秒后打印456
// reject('789') // 3秒后打印789
}, 3000)
}) // return中的promise狀態(tài)發(fā)生改變后才會繼續(xù)執(zhí)行
}).then(res => {
console.log(res) // 3秒后打印456
}).catch(err => {
console.log(err) // 3秒后打印789
})
==return中的promise狀態(tài)發(fā)生改變后才會繼續(xù)執(zhí)行==
return中肯定是返回一個Promise的靶瘸,但是返回任何其他的值苫亦,都是一個成功的回調(diào),只有new Promise的時候會等待
new Promise(function(resolve, reject){
resolve('123')
}).then(res => {
return setTimeout(function(){
console.log(888) // 3秒后打印888
}, 3000)
}).then(res => {
console.log(res) // 不會等待怨咪,直接打印一串?dāng)?shù)字屋剑,
}).catch(err => {
console.log // 不會進(jìn)入這里
})
Javascript 異步機(jī)制
Javascript執(zhí)行順序
- JavaScript先掃描一遍代碼
- 主線程,宏任務(wù)隊列惊暴,微任務(wù)隊列
- 主線程執(zhí)行完一遍饼丘,先查詢微任務(wù)隊列,如果有任務(wù)辽话,執(zhí)行完畢
- 再查詢宏任務(wù)隊列肄鸽,如果宏任務(wù)隊列有任務(wù)卫病,將宏任務(wù)中的一個任務(wù)拿到主線程,將其執(zhí)行典徘,執(zhí)行完再詢問微任務(wù)蟀苛。。逮诲。以此類推
舉例
Promise屬于微任務(wù)
setTimeout屬于宏任務(wù)
setTimeout(() => {
console.log('set1')
});
let p1 = new Promise((resolve, reject) => {
console.log('promise1')
})
setTimeout(() => {
console.log('set2')
})
p1.then(() => {
console.log('then1')
})
console.log(2)
執(zhí)行結(jié)果
promise1
2
then1
set1
set2
- set1入宏任務(wù)隊列
- p1 (new Promise) 同步,直接執(zhí)行 // promise1
- set2入宏任務(wù)隊列
- p1.then 異步 入微任務(wù)隊列
- console 2 直接執(zhí)行 // 2
- 執(zhí)行微任務(wù)隊列 p1.then // then1
- 宏任務(wù)set1取出至主線程執(zhí)行 // set1
- 微任務(wù)空帜平,宏任務(wù)set2取出至主線程執(zhí)行 // set2
- 結(jié)束
setTimeout(() => {
console.log('set1')
new Promise((resolve, reject) => {
console.log('promise2')
resolve(2)
}).then(res => {
console.log('then2')
})
});
let p1 = new Promise((resolve, reject) => {
console.log('promise1')
resolve(2)
})
setTimeout(() => {
console.log('set2')
})
p1.then((res) => {
console.log('then1')
})
console.log(2)
執(zhí)行結(jié)果
promise1
2
then1
set1
promimse2
then2
set2
- 掃描
- set1入宏任務(wù)隊列
- p1同步直接執(zhí)行 // promise1
- set2入宏任務(wù)隊列
- p1.then異步入微任務(wù)隊列
- console 2 直接執(zhí)行 // 2
- 微任務(wù)隊列p1.then執(zhí)行 // then1
- 宏任務(wù)set1取出至主線程執(zhí)行,promise2同步直接執(zhí)行梅鹦,promise2.then異步 入微任務(wù) // set1 , promise2
- 主線程執(zhí)行完畢裆甩,找微任務(wù),執(zhí)行promise2.then // then2
- 宏任務(wù)set2取出至主線程執(zhí)行 // set2
自己實現(xiàn)一個promise
// 回調(diào)函數(shù)里執(zhí)行resolve - then方法把回調(diào)加入resolveArr-執(zhí)行整個resolveArr齐唆,并且改變狀態(tài)返回新的promise
var isFunction = function(fn) {
if (typeof fn === 'function') {
return true
} else {
return false
}
}
Function.prototype.bind = function(context) {
var self = this
return function() {
// call 明確知道參數(shù)有多少嗤栓, apply 參數(shù)不定的情況下使用
self.apply(context, arguments)
}
}
// 通過then 注冊一個任務(wù)回調(diào), resolve觸發(fā)箍邮,執(zhí)行這個then的注冊函數(shù)
function mypromise(handle) {
this.status = 'PENDING' // 狀態(tài)
this.val = undefined // 值茉帅,resolve 的參數(shù)
this.resolveArr = [] // 回調(diào)隊列,then里面定義的方法加入到此
this.rejectArr = [] // reject回調(diào)隊列
this.resolve = function(val) {
// 執(zhí)行resolveArr锭弊, 改變mypromise狀態(tài)
if (this.status !== 'PENDING') return // 狀態(tài)不可逆由此控制
this.status = 'RESOLVE'
this.val = val
let cb;
setTimeout(() => { // resolveArr中所有全部執(zhí)行 then在這里變成異步(重要)
while (cb = this.resolveArr.shift()) { // 把resolveArr第一個賦值給cb 有的話就是ture
if (isFunction(cb)) {
cb(val)
}
}
})
}
this.reject = function(err) {
if (this.status !== 'PENDING') return // 狀態(tài)不可逆由此控制
this.status = 'REJECT'
this.val = err
}
// then里面拋出錯誤的話堪澎,如果不在catch里進(jìn)行處理,就拿不到這個錯誤
try{
// this.resolve味滞,相當(dāng)于把this.resolve方法取出來樱蛤,傳給handle,handle調(diào)用的時候this指向window 所以bind this
handle(this.resolve.bind(this), this.reject)
} catch(err) {
throw err
}
}
// then 方法是promise對象調(diào)用桃犬,所以要放在prototype里
mypromise.prototype.then = function(suc, err) {
const val = this.val
const status = this.status
return new mypromise((sucnext, errnext) => {
// 享元模式 優(yōu)化 先找出不一樣的拿出來定義刹悴,再把一樣的取出來,把不一樣的配進(jìn)去
let _fn = undefined
let _handle = undefined
let run = function() {
try{
console.log(123)
if (!isFunction(_handle)) { // then傳進(jìn)的不是function時直接給出去
_fn(val)
} else {
let res = _handle(val)
console.log(sucnext)
sucnext(res)
}
} catch(err) {
errnext(err) // then 拋出錯誤catch到攒暇, 所以reject
}
}
// let success = function() {
// try{
// if (!isFunction(suc)) {
// resolve(suc)
// } else {
// let res = suc(val)
// resolve(res)
// }
// } catch(err) {
// reject(err) // then 拋出錯誤catch到土匀, 所以reject
// }
// }
// let fail = function() {
// try{
// if (!isFunction(suc)) {
// reject(suc)
// } else {
// let res = err(val)
// resolve(res)
// }
// } catch(err) {
// reject(err) // then 拋出錯誤catch到, 所以reject
// }
// }
switch (status) {
case 'PENDING':
this.resolveArr.push(suc)
this.rejectArr.push(suc)
break
case 'RESOLVE':
_fn = resolve
_handle = suc
run()
// success()
break
case 'REJECT':
_fn = reject
_handle = err
run()
// fail()
break
}
})
}
new mypromise(function(resolve, reject) {
setTimeout(function() {
resolve(4)
}, 3000)
console.log(33)
}).then(res => {
console.log(res)
})