Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Promises {
- constructor(fn) {
- this.state = 0;
- this.value = undefined;
- this.todos = [];
- fn(() => this.resolve(), () => this.reject());
- }
- resolve(value) {
- if (this.state !== 0) return;
- this.state = 1;
- this.value = value;
- this.run();
- }
- reject(reason) {
- if (this.state !== 0) return;
- this.state = 2;
- this.value = reason;
- this.run();
- }
- run() {
- let callbackName, resolver;
- if (this.state === 0) return;
- if (this.state === 1) {
- callbackName = 'onFulfilled';
- resolver = 'resolve';
- }
- if (this.state === 2) {
- callbackName = 'onRejected';
- resolver = 'reject';
- }
- setTimeout(() => {
- this.todos.forEach(todo => {
- try {
- let cb = todo[callbackName];
- if (cb) todo.resolve(cb(this.value));
- else todo[resolver](this.value);
- } catch (e) {
- todo.reject(e);
- }
- this.todos.shift();
- });
- });
- }
- then(onFulfilled, onRejected) {
- let todo = new Promises(() => {});
- todo.onFulfilled =
- typeof onFulfilled === 'function' ? onFulfilled : null;
- todo.onRejected = typeof onRejected === 'function' ? onRejected : null;
- this.todos.push(todo);
- this.run();
- return todo;
- }
- }
Add Comment
Please, Sign In to add comment