promise
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| class MyPromise { constructor(fn){ this.callbacks = [] const resolve = (value) => { this.data = value while(this.callbacks.length) { let cb = this.callbacks.shift() cb(value) } } fn(resolve) } then(onResolvedCallback) { return new MyPromise((resolve) => { this.callbacks.push(() => { const res = onResolvedCallback(this.data) if (res instanceof MyPromise) { res.then(resolve) } else { resolve(res) } }) }) } }
new MyPromise((resolve) => { setTimeout(() => { resolve(1) }, 1000) }).then((res) => { console.log(res) return new MyPromise((resolve) => { setTimeout(() => { resolve(2) }, 1000) }) }).then(res =>{console.log(res)})
|
promise.all
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| MyPromise.all = function (promisesList) { return new MyPromise((resolve, reject) => { if (!Array.isArray(promiselList) return reject(new Error('必须是数组')) if (!promisesList.length) return resolve([]) let arr = [], count = 0 for (let i = 0, len = promisesList.length; i < len; i++) { Promise.resolve(promise).then(result => { count++ arr[i] = result if(count === len) resolve(arr) }).catch(err => reject(err)) } }) }
|
promise.race
传参和上面的 all 一模一样,传入一个 Promise 实例集合的数组,然后全部同时执行,谁先快先执行完就返回谁,只返回一个结果
1 2 3 4 5 6 7 8 9 10
| MyPromise.race = function(promisesList) { return new MyPromise((resolve, reject) => { for (const promise of promisesList) { promise.then(resolve, reject) } }) }
|