Promise標(biāo)準(zhǔn)了解一下
傳送門1?? ??Promises/A+規(guī)范
傳送門2?? ??阮一峰前輩ECMAScript 6入門——Promise對象
Promise重點(diǎn)難點(diǎn)
Promise的狀態(tài)不受外界影響,只由Promise內(nèi)的異步操作結(jié)果決定。
-
Promise的狀態(tài)一旦改變就不會再變。
- pending ?? fulfilled
- pending ?? rejected
Promise的構(gòu)造函數(shù)是同步的,then()方法中的函數(shù)是異步的。
then()方法或者catch()方法的參數(shù)期望是函數(shù),傳入非函數(shù)則會發(fā)生值穿透
-
Promise屬于microtask,同一次事件循環(huán)中,microtask永遠(yuǎn)在macrotask之前執(zhí)行。
手寫promise
- 實(shí)現(xiàn)基本狀態(tài)(pending, fulfilled, rejected)
- 實(shí)現(xiàn)then方法
- 返回一個promise,實(shí)現(xiàn)鏈?zhǔn)秸{(diào)用
- 實(shí)現(xiàn)狀態(tài)判斷
- 實(shí)現(xiàn)resolve函數(shù)
- 接受一個Promise作為參數(shù)時的情況,實(shí)現(xiàn)鏈?zhǔn)絇romise
- 執(zhí)行回調(diào)函數(shù)時使用setTimeout,保證在注冊then方法后觸發(fā)
- 實(shí)現(xiàn)Promise.all,Promise.race方法
(function (window) {
var Promise = function (fn) {
var value = null;
var callbacks = [];
var state = 'pending'; // pending, fulfilled, rejected
var promise = this;
// 注冊then事件,供resolve后調(diào)用
promise.then = function (onFulfilled, onRejected) {
// 返回promise實(shí)現(xiàn)鏈?zhǔn)絧romise調(diào)用
return new Promise(function (resolve, reject) {
handle({
onFulfilled: onFulfilled || null,
onRejected: onRejected || null,
resolve: resolve,
reject: reject
})
})
}
promise.catch = function(onRejected) {
return promise.then(undefined, onRejected)
}
function handle (callback) {
// 狀態(tài)變化前,事件推進(jìn)隊(duì)列里;狀態(tài)一旦變化后不再變動,直接執(zhí)行結(jié)果
if (state === 'pending') {
callbacks.push(callback);
} else {
var cb = state === 'fulfilled' ? callback.onFulfilled : callback.onRejected
// then方法沒有傳遞任何參數(shù)的情況下,返回結(jié)果值
if (!cb) {
cb = state === 'fulfilled' ? callback.resolve : callback.reject;
cb(value)
} else {
try {
var ret = cb(value);
callback.resolve(ret);
} catch (e) {
callback.reject(e)
}
}
}
}
function resolve(newValue) {
// 狀態(tài)一旦改變便不再改變
if (state !== 'pending') return
// 假如resolve了一個promise的話(鏈?zhǔn)絧romise)
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = newValue.then;
if (typeof then === 'function') {
// 調(diào)用第二個promise中的then,遞歸直到不是一個promise值為止
then.call(newValue, resolve, reject);
return
}
}
value = newValue;
state = 'fulfilled';
execute()
}
function reject(reason) {
// 狀態(tài)一旦改變便不再改變
if (state !== 'pending') return
state = 'rejected'
value = reason
execute()
}
function execute() {
// 使用setTimeOut保證resolve一定在then事件注冊后執(zhí)行
setTimeout(() => {
callbacks.forEach(function (callback) {
handle(callback);
})
}, 0);
}
fn(resolve, reject);
}
Promise.all = function (promises) {
if (!Array.isArray(promises)) {
throw new TypeError('請傳入promise數(shù)組')
}
return new Promise(function (resolve, reject) {
var result = [];
var count = promises.length
function reslover (index) {
return function(value) {
resloveAll(index, value)
}
}
function rejecter (reason) {
reject(reason)
}
function resloveAll (index, value) {
result[index] = value
// 等待全部promise執(zhí)行完才執(zhí)行resolve一個數(shù)組
if (--count === 0) {
resolve(result)
}
}
promises.forEach(function (promise, index) {
promise.then(reslover(index), rejecter)
})
})
}
Promise.race = function (promises) {
if (!Array.isArray(promises)) {
throw new TypeError('請傳入promise數(shù)組')
}
return new Promise(function (resolve, reject) {
function reslover (value) {
resolve(value)
}
function rejecter (reason) {
reject(reason)
}
promises.forEach(function (promise, index) {
promise.then(reslover, rejecter)
})
})
}
window.Promise = Promise
})(window)
/******************************************實(shí)例 */
function test(i) {
return new Promise(function (resolve) {
setTimeout(() => {
resolve(i);
}, 1000);
})
}
function test2(i) {
return new Promise(function (resolve, reject) {
setTimeout(() => {
if (i % 2) {
resolve(i);
} else {
reject(i);
}
}, 2000);
})
}
// 鏈?zhǔn)絇romise
test(1).then(test2).then(function (something) {
console.log('case1: success!' + something);
}).catch(function (something) {
console.log('case1: failed!' + something);
})
// Promise.all
Promise.all([test(2), test2(4)]).then(function (something) {
console.log('case2: success!' + something);
}).catch(function (something) {
console.log('case2: failed!' + something)
})
// Promise.race
Promise.race([test(3), test2(5)]).then(function (something) {
console.log('case3: success!' + something);
}).catch(function (something) {
console.log('case3: failed!' + something)
})
// 多次改變狀態(tài),只有第一次生效
function test3 () {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success1')
reject('error')
resolve('success2')
},0)
})
}
test3().then((res) => {
console.log('then: ', res)
})
// 一旦改變狀態(tài)后,多次調(diào)用then()方法也只會馬上得到Promise返回的值,Promise構(gòu)造函數(shù)不會多次執(zhí)行
function test4 () {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success')
}, 1000)
})
}
const start = Date.now()
test4().then((res) => {
console.log(res, Date.now() - start)
})
test4().then((res) => {
console.log(res, Date.now() - start)
})