promise
是什么
Promise
是用于处理异步操作的对象。它有三种状态:pending
(进行中)、fulfilled
(已成功)和 rejected
(已失败)。我们可以手写一个简化版的 Promise
,实现其基本功能。
实现思路:Promise
构造函数接收一个执行器函数,该函数有两个参数 resolve
和 reject
,用于改变 Promise
的状态。then
方法用于注册回调函数,在 Promise
的状态改变后执行。 使用状态机来管理 pending
、fulfilled
和 rejected
状态。
实现
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 class MyPromise {hexp constructor (executor ) { this .state = 'pending' ; this .value = undefined ; this .reason = undefined ; this .onFulfilledCallbacks = []; this .onRejectedCallbacks = []; const resolve = (value ) => { if (this .state === 'pending' ) { this .state = 'fulfilled' ; this .value = value; this .onFulfilledCallbacks .forEach (fn => fn (this .value )); } }; const reject = (reason ) => { if (this .state === 'pending' ) { this .state = 'rejected' ; this .reason = reason; this .onRejectedCallbacks .forEach (fn => fn (this .reason )); } }; try { executor (resolve, reject); } catch (error) { reject (error); } } then (onFulfilled, onRejected ) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value; onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason }; if (this .state === 'fulfilled' ) { onFulfilled (this .value ); } if (this .state === 'rejected' ) { onRejected (this .reason ); } if (this .state === 'pending' ) { this .onFulfilledCallbacks .push (onFulfilled); this .onRejectedCallbacks .push (onRejected); } } } const promise = new MyPromise ((resolve, reject ) => { setTimeout (() => { resolve ('Success!' ); }, 1000 ); }); promise.then ( value => console .log ('Fulfilled:' , value), reason => console .log ('Rejected:' , reason) );
promise.all
是什么
Promise.all() 是一个用于并行处理多个 Promise 的方法,它接受一个包含多个 Promise 的可迭代对象,并返回一个新的 Promise。只有当所有 Promise 都成功时,这个新的 Promise 才会 resolve;如果其中任何一个 Promise 失败,Promise.all() 就会 reject,并返回第一个失败的 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 function promiseAll (promises ){ return new Promise ((resolve,reject )=> { if (!Array .isArray (promises)) return reject (new TypeError ('参数类型应该为数组' )) if (promises.length ==0 ) return resolve ([]) let resultArr = [] let completedPromises = 0 promises.forEach ((promise,index )=> { Promise .resolve (promise) .then (result => { resultArr[index] = result completedPromises ++ if (completedPromises==promises.length ) resolve (resultArr) }) .catch (error => reject (error)) }) }) } const p1 = Promise .resolve (3 )const p2 = new Promise ((resolve ) => setTimeout (resolve, 1000 , 'foo' ))const p3 = Promise .resolve (42 )promiseAll ([p1, p2, p3]) .then ((results ) => console .log (results)) .catch ((err ) => console .log (err))
promise.race
是什么
Promise.race() 方法会返回一个新的 Promise,一旦传入的 Promise 中有一个完成(无论是 resolved 还是 rejected),就会立即以那个 Promise 的结果(resolved 或 rejected)进行决议。
实现
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 function promiseRace (promises ) { return new Promise ((resolve, reject ) => { if (!Array .isArray (promises)) { return reject (new TypeError ('Argument must be an array' )); } if (promises.length === 0 ) { return ; } promises.forEach (promise => { Promise .resolve (promise) .then (resolve) .catch (reject); }); }); } const p1 = new Promise ((resolve ) => setTimeout (resolve, 500 , "First" ));const p2 = new Promise ((resolve ) => setTimeout (resolve, 100 , "Second" ));const p3 = new Promise ((resolve, reject ) => setTimeout (reject, 200 , "Error" ));promiseRace ([p1, p2, p3]) .then (result => console .log (result)) .catch (err => console .log (err));