promise
是異步編程的一種解決方法,比傳統的回調函數和事件更合理更強大。
他由社區最早提出和實現,ES6將其寫進語言標準,統一了用法,原生提供了Promise
對象。
所謂promise
,簡單說是一個容器,裏面保存着某個未來纔會結束的事件(通常是一個異步操作)的結果
從語法上說,promise
是一個對象,從它可以獲取異步操作的消息,
promise
提供了統一的API,各種異步操作都可以用同樣的方法進行處理。
Promise 表示一個異步操作的最終結果,與之進行交互的方式主要是 then 方法,該方法註冊了兩個回調函數,用於接收 promise 的終值或本 promise 不能執行的原因。
Promise
的實現遵循 Promises/A+
規範,詳細內容:
英文版:https://promisesaplus.com/
中文版1:https://www.ituring.com.cn/article/66566
中文版2:https://segmentfault.com/a/1190000002452115
原生Promise
使用方法:
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
}, 300);
});
promise1.then((value) => {
console.log(value); // expected output: "foo"
});
手寫實現:
// 狀態定義
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
// Promise 解決過程
const resolvePromise = (promise, x, resolve, reject) => {
// 如果 promise 和 x 指向同一對象,以 TypeError 爲據因拒絕執行 promise
if (promise === x) {
return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
}
let called;
// 後續的條件要嚴格判斷 保證代碼能和別的庫一起使用
if ((typeof x === 'object' && x != null) || typeof x === 'function') {
try {
// 爲了判斷 resolve 過的就不用再 reject 了(比如 reject 和 resolve 同時調用的時候) Promise/A+ 2.3.3.1
let then = x.then;
if (typeof then === 'function') {
// 不要寫成 x.then,直接 then.call 就可以了 因爲 x.then 會再次取值,Object.defineProperty Promise/A+ 2.3.3.3
then.call(x, y => { // 根據 promise 的狀態決定是成功還是失敗
if (called) return;
called = true;
// 遞歸解析的過程(因爲可能 promise 中還有 promise) Promise/A+ 2.3.3.3.1
resolvePromise(promise, y, resolve, reject);
}, r => {
// 只要失敗就失敗 Promise/A+ 2.3.3.3.2
if (called) return;
called = true;
reject(r);
});
} else {
// 如果 x.then 是個普通值就直接返回 resolve 作爲結果 Promise/A+ 2.3.3.4
resolve(x);
}
} catch (e) {
// Promise/A+ 2.3.3.2
if (called) return;
called = true;
reject(e)
}
} else {
// 如果 x 是個普通值就直接返回 resolve 作爲結果 Promise/A+ 2.3.4
resolve(x)
}
}
class MyPromise {
constructor(executor) {
this.state = PENDING;
this.onResloveList = []
this.onRejectList = []
this.value = undefined;
this.reason = undefined;
let resolve = (value) => {
if (this.state == PENDING) {
this.state = FULFILLED;
this.value = value;
this.onResloveList.forEach(fn => fn())
}
}
let reject = (reason) => {
if (this.state == PENDING) {
this.state = REJECTED;
this.reason = reason;
this.onRejectList.forEach(fn => fn())
}
}
try {
executor(resolve, reject)
} catch (error) {
console.log('catch...' + error)
reject(error)
}
}
then(onFulfilled, onRejected) {
// 值穿透
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v
onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err }
let thenPromise = new MyPromise((resolve, reject) => {
switch (this.state) {
case PENDING: // 執行狀態
this.onResloveList.push((value) => {
try {
let x = onFulfilled(this.value)
resolvePromise(thenPromise, x, resolve, reject)
} catch (e) {
reject(e)
}
})
this.onRejectList.push((value) => {
try {
let x = onRejected(this.reason)
resolvePromise(thenPromise, x, resolve, reject)
} catch (e) {
reject(e)
}
})
break;
case FULFILLED: // 完成狀態
setTimeout(() => {
try {
let x = onFulfilled(this.value)
resolvePromise(thenPromise, x, resolve, reject)
} catch (e) {
reject(e)
}
}, 0);
break;
case REJECTED: // 失敗狀態
setTimeout(() => {
try {
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e)
}
}, 0);
break;
default:
break;
}
})
return thenPromise
}
catch = (rejected) => {
this.then(null, rejected)
}
}
驗證:
new MyPromise((resolve, reject) => {
console.log(0, 'create')
setTimeout(() => {
console.log(1, 'timeout')
resolve('123')
}, 500);
})
.then(res => {
console.log(2, res)
return res
})
.then(res => {
console.log(3, res)
return res
})
.then()
.then(res => {
console.log(4, res)
return new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('456')
}, 500);
})
})
.then(res => {
console.log(5, res)
return res
})
.then(res => {
console.log(6, res)
console.log(a)
})
.catch(err => {
console.log(7, err)
})
// 輸出:
// 0 "create"
// 1 "timeout"
// 2 "123"
// 3 "123"
// 4 "123"
// 5 "456"
// 6 "456"
// 7 ReferenceError: a is not defined
原生Promise
的實現是微任務,本文用setTimeout
替代實現