From 8529e1a0ffa294b6ad465a293a18601de43870a9 Mon Sep 17 00:00:00 2001 From: june6723 Date: Sun, 5 Feb 2023 22:28:36 +0900 Subject: [PATCH] =?UTF-8?q?:sparkles:=20=EB=B9=84=EB=8F=99=EA=B8=B0=20?= =?UTF-8?q?=EC=A7=80=EC=9B=90=20Promise=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/june/promise.js | 57 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/june/promise.js diff --git a/src/june/promise.js b/src/june/promise.js new file mode 100644 index 0000000..4c2e674 --- /dev/null +++ b/src/june/promise.js @@ -0,0 +1,57 @@ +class Promise { + constructor(callback) { + this.state = 'pending'; + this.onFulfilledCallback = null; + this.onRejectedCallback = null; + const resolve = value => { + this.state = 'fulfilled'; + this.value = value; + if (this.onFulfilledCallback !== null) { + this.onFulfilledCallback(value); + } + }; + const reject = value => { + this.state = 'rejected'; + this.value = value; + if (this.onRejectedCallback !== null) { + this.onRejectedCallback(value); + } + }; + callback(resolve, reject); + } + + then(callback) { + if (this.state === 'pending') { + this.onFulfilledCallback = callback; + } + if (this.state === 'fulfilled') { + callback(this.value); + } + return this; + } + + catch(callback) { + if (this.state === 'pending') { + this.onRejectedCallback = callback; + } + if (this.state === 'rejected') { + callback(this.value); + } + return this; + } + getValue() { + return this.value; + } +} + +function asyncResolve() { + return new Promise((resolve, reject) => { + setTimeout(() => resolve('resolved after 1s'), 1000); + }); +} + +asyncResolve().then(result => console.log(result)); + +asyncResolve() + .then(result => `next ${result}`) + .then(result => console.log(`should log "next result" but ${result} logged`));