How to implement a simple Promise
Today, I will talk to you about how to achieve a simple Promise. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.
A simple rough implementation of Promise, the key point is
When pending, the thenable function is maintained by a queue. When the state changes to resolved (fulfilled), all thenable functions in the queue execute. When resolved, the thenable function executes directly.
The same is true of rejected statu
Class Prom {
Static resolve (value) {
If (value & & value.then) {
Return value
}
Return new Prom (resolve = > resolve (value))
}
Constructor (fn) {
This.value = undefined
This.reason = undefined
This.status = 'PENDING'
/ / maintain a resolve/pending function queue
This.resolveFns = []
This.rejectFns = []
Const resolve = (value) = > {
/ / Note the setTimeout here
SetTimeout () = > {
This.status = 'RESOLVED'
This.value = value
This.resolveFns.forEach (({fn, resolve: res, reject: rej}) = > res (fn (value)
})
}
Const reject = (e) = > {
SetTimeout () = > {
This.status = 'REJECTED'
This.reason = e
This.rejectFns.forEach (({fn, resolve: res, reject: rej}) = > rej (fn (e)
})
}
Fn (resolve, reject)
}
Then (fn) {
If (this.status = = 'RESOLVED') {
Const result = fn (this.value)
/ / A Promise needs to be returned
/ / if the status is resolved, execute it directly
Return Prom.resolve (result)
}
If (this.status = = 'PENDING') {
/ / A Promise is also returned
Return new Prom ((resolve, reject) = > {
/ / push queue and execute uniformly after resolved
This.resolveFns.push ({fn, resolve, reject})
})
}
}
Catch (fn) {
If (this.status = = 'REJECTED') {
Const result = fn (this.value)
Return Prom.resolve (result)
}
If (this.status = = 'PENDING') {
Return new Prom ((resolve, reject) = > {
This.rejectFns.push ({fn, resolve, reject})
})
}
}
}
Prom.resolve (10) .then (o = > o * 10) .then (o = > o + 10) .then (o = > {
Console.log (o)
})
Return new Prom ((resolve, reject) = > reject ('Error')) .catch (e = > {
Console.log ('Error', e)
}) after reading the above, do you have any further understanding of how to implement a simple Promise? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.