howprogrammingworks / promise Goto Github PK
View Code? Open in Web Editor NEWAsynchronous Programming with Promises
Home Page: https://www.youtube.com/TimurShemsedinov
License: MIT License
Asynchronous Programming with Promises
Home Page: https://www.youtube.com/TimurShemsedinov
License: MIT License
I have implemented Promise. Should I commit here as learning material?
"use strict";
const STATUS = {
PENDING: "pending",
FULFILLED: "fulfilled",
REJECTED: "rejected",
};
class MyPromise {
_status = STATUS.PENDING;
_value = undefined;
_subs = [];
_resolve = (value) => {
this._done(value, STATUS.FULFILLED);
};
_reject = (reason) => {
this._done(reason, STATUS.REJECTED);
};
_done = (value, state) => {
// setTimeout need only for UncaughtPromiseError
setTimeout(() => {
if (this._status !== STATUS.PENDING) return;
if (value instanceof MyPromise) {
value.then(this._resolve, this._reject);
return;
}
this._value = value;
this._status = state;
this._runCallbacks();
}, 0);
};
constructor(executor) {
try {
executor(this._resolve, this._reject);
} catch (error) {
this._reject(error);
}
return this;
}
_runCallbacks() {
if (this._status === STATUS.PENDING) return;
// This works only with setTimeout in this._done
const isUncaughtPromiseError =
this._status === STATUS.REJECTED && !this._subs.length;
if (isUncaughtPromiseError) {
// You can emit error instead of throw like:
// process.emit("unhandledRejection", this._value, this);
throw new UncaughtPromiseError(this._value);
}
while (this._subs.length) {
const sub = this._subs.shift();
const callback = sub[this._status];
callback(this._value);
}
}
_subscribe(onFulfilledCallback, onRejectedCallback) {
const sub = {
[STATUS.FULFILLED]: onFulfilledCallback,
[STATUS.REJECTED]: onRejectedCallback,
};
this._subs.push(sub);
}
then(onFulfilled = null, onRejected = null) {
return new MyPromise((resolve, reject) => {
const onFulfilledCallback = (value) => {
if (!onFulfilled) {
resolve(value);
return;
}
try {
resolve(onFulfilled(value));
} catch (error) {
reject(error);
}
};
const onRejectedCallback = (reason) => {
if (!onRejected) {
reject(reason);
return;
}
try {
resolve(onRejected(reason));
} catch (error) {
reject(error);
}
};
this._subscribe(onFulfilledCallback, onRejectedCallback);
this._runCallbacks();
});
}
catch(onRejected = null) {
return this.then(null, onRejected);
}
finally(onFinally = null) {
return new MyPromise((resolve, reject) => {
const onFinallyCallback = () => {
if (!onFinally) return;
try {
onFinally();
} catch (error) {
console.error(error);
}
};
const onFulfilledCallback = (value) => {
onFinallyCallback();
resolve(value);
};
const onRejectedCallback = (reason) => {
onFinallyCallback();
reject(reason);
};
this._subscribe(onFulfilledCallback, onRejectedCallback);
this._runCallbacks();
});
}
static resolve(value) {
return new MyPromise((resolve) => resolve(value));
}
static reject(reason) {
return new MyPromise((_, reject) => reject(reason));
}
static allSettled(promises) {
const length = promises.length;
const result = new Array(length).fill(null);
let completedPromises = 0;
return new MyPromise((resolve) => {
for (let i = 0; i < length; i++) {
promises[i]
.then(
(value) => {
result[i] = { status: STATUS.FULFILLED, value };
},
(reason) => {
result[i] = { status: STATUS.REJECTED, reason };
}
)
.finally(() => {
completedPromises++;
if (completedPromises === length) resolve(result);
});
}
});
}
static all(promises) {
const length = promises.length;
const result = new Array(length).fill(null);
let completedPromises = 0;
return new MyPromise((resolve, reject) => {
for (let i = 0; i < length; i++) {
promises[i]
.then((value) => {
result[i] = value;
completedPromises++;
if (completedPromises === length) resolve(result);
})
.catch(reject);
}
});
}
static any(promises) {
const length = promises.length;
const errors = new Array(length).fill(null);
let errorsPromises = 0;
return new MyPromise((resolve, reject) => {
for (let i = 0; i < length; i++) {
promises[i]
.catch((reason) => {
errors[i] = reason;
errorsPromises++;
if (errorsPromises === length) reject(errors);
})
.then(resolve);
}
});
}
static race(promises) {
return new MyPromise((resolve, reject) => {
for (let i = 0; i < promises.length; i++) {
promises[i].then(resolve, reject);
}
});
}
}
class UncaughtPromiseError extends Error {
constructor(error) {
super(error);
this.stack = `UncaughtPromise${error.stack}`;
}
}
module.exports = MyPromise;
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.