Skip to content

Instantly share code, notes, and snippets.

@Mango3403
Created September 13, 2021 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mango3403/594d4603cc2a21738263e7488658d408 to your computer and use it in GitHub Desktop.
Save Mango3403/594d4603cc2a21738263e7488658d408 to your computer and use it in GitHub Desktop.
JavaScript Promise
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