Created
September 13, 2021 12:47
-
-
Save Mango3403/594d4603cc2a21738263e7488658d408 to your computer and use it in GitHub Desktop.
JavaScript Promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyPromise { | |
callbacks = [] | |
state = 'pending' | |
value = null | |
constructor(fn) { | |
fn(this._resolve.bind(this)) | |
} | |
then(onFulfilled) { | |
return new Promise(resolve => { | |
this._handle({ | |
onFulfilled: onFulfilled || null, | |
resolve: resolve | |
}) | |
}) | |
} | |
_handle(callback) { | |
if (this.state === 'pending') { | |
this.callbacks.push(callback) | |
return; | |
} | |
// 如果then没有传递任何东西 | |
if (!callback.onFulfilled) { | |
callback.resolve(this.value); | |
return; | |
} | |
var ret = callback.onFulfilled(this.value); | |
callback.resolve(ret); | |
} | |
_resolve(value) { | |
this.state = 'fulfilled'; | |
this.value = value | |
this.callbacks.forEach(callback => this._handle(callback)) | |
} | |
} | |
// 测试 | |
const mockAjax = (url, s, callback) => { | |
setTimeout(() => { | |
callback(url + '异步请求耗时' + s + '秒') | |
}, s * 1000) | |
} | |
new MyPromise(resolve => { | |
mockAjax('getUserId', 1, function (result) { | |
resolve(result) | |
}) | |
}).then(result => { | |
console.log(result); | |
return new Promise(resolve => { | |
mockAjax('getAgentId', 2, function (result) { | |
resolve(result) | |
}) | |
}) | |
}).then(result => { | |
console.log(result); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment