diff --git "a/HTML5 \346\213\226\346\224\276/index.html" "b/HTML5 \346\213\226\346\224\276/index.html" index f190941..76d86ab 100644 --- "a/HTML5 \346\213\226\346\224\276/index.html" +++ "b/HTML5 \346\213\226\346\224\276/index.html" @@ -113,4 +113,52 @@

拖放(Drag 和 drop)

- \ No newline at end of file + +script sta +async1 start +async2 start 遇到settimeout 加入到宏任务 +new promise +script end +promise1 +promise2 +async2 end +async1 end' +settimeout + \ No newline at end of file diff --git a/index.html b/index.html index fde8984..1441e42 100644 --- a/index.html +++ b/index.html @@ -9,16 +9,39 @@
- + + \ No newline at end of file diff --git "a/\345\256\236\347\216\260\344\270\200\344\270\252\347\256\200\345\215\225\347\232\204promise.js" "b/\345\256\236\347\216\260\344\270\200\344\270\252\347\256\200\345\215\225\347\232\204promise.js" index 51d2465..2ecfd16 100644 --- "a/\345\256\236\347\216\260\344\270\200\344\270\252\347\256\200\345\215\225\347\232\204promise.js" +++ "b/\345\256\236\347\216\260\344\270\200\344\270\252\347\256\200\345\215\225\347\232\204promise.js" @@ -39,3 +39,95 @@ // .then(console.log) //极简型 + +/** + * excutor 执行器函数(同步) + */ +!function(){ + function Promise(excutor) { + this.status = 'pendding' + this.data = undefined + this.callbacks = [] //{onResloved:() => {}, onRejected:() => {}} + // let _this = this + const resolve = (value) => { + if(this.status !== 'pendding') return + this.status = 'resolved' + this.data = value + if(this.callbacks.length > 0) { + setTimeout(() => { + this.callbacks.forEach(cbObj => { + cbObj['onResolved'](value) + }) + },0) + } + } + + const reject = (reason) => { + if(this.status !== 'pendding') return + this.status = 'rejected' + this.data = reason + if(this.callbacks.length > 0) { + setTimeout(() => { + this.callbacks.forEach(cbObj => { + cbObj['onRejected'](value) + }) + },0) + } + } + try { + excutor(resolve, reject) + }catch(err) { + reject(err) + } + } + + Promise.prototype.then = function(onResolved, onRejected) { + return new Promise((resolve, reject) => { + // console.log(this.status) + if(this.status === 'pendding') { + this.callbacks.push({onResolved, onRejected}) + } else if(this.status === 'resolved') { + setTimeout(() => { + try { + const res = onResolved(this.data) + if(res instanceof Promise) { + // res.then(value => resolve(value), err => reject(err)) + res.then(resolve, reject) + } else { + resolve(res) + } + } catch (error) { + reject(error) + } + }) + } else { + setTimeout(() => { + onRejected(this.data) + }) + } + }) + } + + + Promise.prototype.catch = function(onRejected) { + + } + + Promise.resolve = function(value) { + + } + + Promise.rejected = function(reason) { + + } + + Promise.all = function(promises) { + + } + + Promise.race = function(promises) { + + } + window.Promise = Promise +}(window) +