简易 Promise 实现
简易的原因是只有一次 then()
,代码如下:
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 41 42 43 44 45 46
| class Promise2 { #status = 'pending'; constructor(fn) { this.q = []; const resolve = (data) => { this.#status = 'fulfilled'; const f1f2 = this.q.shift(); if (!f1f2 || !f1f2[0]) return; const x = f1f2[0].call(undefined, data); if (x instanceof Promise2) { x.then( (data) => { resolve(data); }, (reason) => { reject(reason); } ); } else { resolve(x); } }; const reject = (reason) => { this.#status = 'rejected'; const f1f2 = this.q.shift(); if (!f1f2 || !f1f2[1]) return; const x = f1f2[1].call(undefined, reason); if (x instanceof Promise2) { x.then( (data) => { resolve(data); }, (reason) => { reject(reason); } ); } else { resolve(x); } }; fn.call(undefined, resolve, reject); } then(f1, f2) { this.q.push([f1, f2]); } }
|
使用示例如下:
| const p = new Promise2(function (resolve, reject) { setTimeout(function () { reject('出错'); }, 3000); }); p.then( (data) => { console.log(data); }, (r) => { console.error(r); } );
|
详细可看:面试官:“你能手写一个 Promise 吗” - 知乎 (zhihu.com)
手写 Promise.all
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| Promise.myAll = function (promiseList) { return new Promise((resolve, reject) => { const resultList = []; let count = 0; promiseList.map((promise, index) => { promise.resolve( (result) => { resultList[index] = result; count += 1; if (count === promiseList.length - 1) { resolve(resultList); } }, (reason) => { reject(reason); } ); }); }); };
|
要点如下:
- 了解 all 的参数和返回值
- 用数组来记录结果
- 只要有一个 reject 就整体 reject