Realize a Promise according to Promises/A+.
Basic
- new Promise instance
- execute the function and execute the callback function according to the result
1 | function MyPromise(fn) { |
Support Sync Task
1 | function resolve(value) { |
Support Three Status
- realize three status: pending, fulfilled, rejected
- realize two changes: pending to fulfilled, pending to rejected
- once the status changed, add then will get the result directly
1 | const PENDING = "pending"; |
Support Chain Operation
use Array to store callback
1 | self.onFulfilledCallbacks = []; |
traverse array to execute callback
1 | self.onFulfilledCallbacks.forEach((callback) => callback(self.value)); |
return this in then()
1 | MyPromise.prototype.then = function(onFulfilled, onRejected) { |
Support Serial Asynchronous Operation
1 |
|
Promise/A+ Test
1 | function resolvePromise(bridgePromise, x, resolve, reject) { |
all,race,resolve,reject
1 | MyPromise.all = function(promises) { |
Code
The whole code can be found in here