Last active
March 16, 2023 07:08
-
-
Save fukurouzhong/6fd18c72412dd7e92ca0e677624a08c8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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