From 4efcae8347304b66ee5a6b064a29714aa048e825 Mon Sep 17 00:00:00 2001 From: caojunjie <1301239018@qq.com> Date: Fri, 27 Dec 2024 18:07:45 +0800 Subject: [PATCH] promise-imp --- js-advanced/implement/promise/index.js | 66 ++++++++++++++++++++++++++ js-advanced/implement/promise/test.js | 17 +++++++ 2 files changed, 83 insertions(+) create mode 100644 js-advanced/implement/promise/index.js create mode 100644 js-advanced/implement/promise/test.js diff --git a/js-advanced/implement/promise/index.js b/js-advanced/implement/promise/index.js new file mode 100644 index 0000000..7ade76b --- /dev/null +++ b/js-advanced/implement/promise/index.js @@ -0,0 +1,66 @@ +const Pedding = 'pedding' +const Resolved = 'resolved' +const Rejected = 'rejected' + +class MyPromise { + constructor(executor) { + + this.status = Pedding; + + + const resolve = (data) => { + this.status = Resolved + this.data = data; + return this; + } + + const reject = (data) => { + this.status = Rejected + this.data = data; + return this; + } + + executor(resolve, reject) + } + + then(onFulfilled, onRejected) { + onFulfilled = isFunction(onFulfilled)? onFulfilled: (value) => value; + onRejected = isFunction(onRejected)? onRejected: (value) => { + throw err; + }; + + return new MyPromise((resolve, reject) => { + if(this.status === Resolved) { + onFulfilled(this.data); + }else if(this.status === Rejected) { + onRejected + } + }) + } + + catch() { + + } + + finally() { + + } +} + +function isFunction(fn) { + return fn instanceof Function; +} + + +const abc = new Promise((resolve,reject) => { + resolve(1) +}) + + +abc.then((data) => { + console.log(data); +}) + + + + diff --git a/js-advanced/implement/promise/test.js b/js-advanced/implement/promise/test.js new file mode 100644 index 0000000..11098a7 --- /dev/null +++ b/js-advanced/implement/promise/test.js @@ -0,0 +1,17 @@ +Promise.resolve('good').then((data) => { + console.log(data) +}).then(rst => { + console.log(rst); +}) + +Promise.reject('err').then((data) => { + console.log(data) +},(err) => { + console.log('err: ', err) +}) + +new Promise((resolve, reject) => { + resolve(1); +}).then(data => { + console.log(data); +}) \ No newline at end of file