Skip to content

Instantly share code, notes, and snippets.

@fukurouzhong
Last active March 16, 2023 07:08
Show Gist options
  • Save fukurouzhong/6fd18c72412dd7e92ca0e677624a08c8 to your computer and use it in GitHub Desktop.
Save fukurouzhong/6fd18c72412dd7e92ca0e677624a08c8 to your computer and use it in GitHub Desktop.
const PENDING = 0;
const FULLFILLED = 1;
const REJECTED = 2;
function CustomPromise(executor) {
let state = PENDING;
let value = null;
let handlers = [];
let catches = [];
function resolve(result) {
if(state !== PENDING) return;
state = FULFILLED;
value = result;
handlers.forEach((h) => h(value));
}
function reject(err) {
if(state !== PENDING) return;
state = REJECTED;
value = err;
catches.forEach((c) => c(err));
}
this.then = function (callback) {
if(state === FULFILLED) {
callback(value);
} else {
handlers.push(callback);
}
}
executor(resolve, reject);
}
const doWork = (res, rej) => {
setTimeout(() => { res("Hello World") }, 1000);
}
let someText = new CustomPromise(doWork);
someText.then((val) => {
console.log("1st log:" + val);
})
setTimeout(() => {
someText.then((val) => {
console.log("3st log:" + val);
})
},3000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment