前端面試題 - 如何實現promise?
- 通過構造函數生成一個promise對象,該構造函數有一個延時函數參數
- 通過promise.then()或promise.catch()方法實現結果獲取
- then函數和catch函數可以鏈式調用
function MyPromise(func) {
this.status = 'pending';
this.res = '';
this.thenCbs = [];
this.catchCbs = [];
const resolve = (data) => {
this.status = 'fulfilled';
this.res = data;
this.thenCbs.forEach(cb => {
cb(this.res);
});
}
const reject = (data) => {
this.status = 'rejected';
this.res = data;
this.catchCbs.forEach(cb => {
cb(this.res);
});
}
this.then = function (cb) {
if (this.status == 'pending') {
this.thenCbs.push(cb);
}
if (this.status == 'fulfilled') {
var res = cb(this.res)
}
return this;
}
this.catch = function (cb) {
if (this.status == 'pending') {
this.catchCbs.push(cb)
}
if (this.status == 'rejected') {
var res = cb(this.res)
}
return this;
}
func(resolve, reject)
}
通俗易懂的前端面試題網站: [https://www.front-interview.com](https://www.front-interview.com)