是一个保存着未来才会结束的事件结果的容器
Promiseb包含三种状态pending(进行中)、fullfilled(已完成)、rejected(已失败)
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 41 42 43 44 45 46 47 48 49 50 51 52 53
|
Promise.all([ ])
Promise.allSettle([ ])
Promise.any([ 'cdn1', 'cdn2', 'cdn3' ]).then() Promise.any([ '抢票地址1', '抢票地址2' ]).then()
function selfFetch(api, { timeout }) { return Promise.race([ new Promise(resolve => { setTimeout(() => { resolve(`fetch ${api} success`, ); }, 500); }), new Promise((resolve, reject) => { setTimeout(() => { reject(`fetch ${api} timeout`) }, timeout) }) ]) }
selfFetch('/api/user', { timeout: 1000 }).then(res => { console.log('success', res); }).catch(error => { console.log('error', error); })
|
手写promise: ES5版
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
| function MyPromise (executor) { this.state = 'pending' this.value = undefined
this.callbacks = []
const resolve = (value) => { if(this.state === 'pending') { this.state = 'fulfilled' this.value = value this.callbacks.forEach((handle)=>{ handle.onFulfilled(value) }) } } const reject = (value) => { if(this.state === 'pending') { this.state = 'rejected' this.value = value this.callbacks.forEach((handle)=>{ handle.onRejected(value) }) } }
try { executor(resolve, reject) } catch(e) { reject(e) } MyPromise.prototype.then = function (onFulfilled, onRejected) { if (this.state === 'fulfilled') { onFulfilled(this.value) } else if(this.state === 'rejected') { onRejected(this.value) } else { this.callbacks.push({ onFulfilled, onRejected }) console.log(this.callbacks) } } }
const p1 = new MyPromise((resolve, reject)=>{ setTimeout(()=>{ resolve('成功') },2000) }) p1.then((res)=>{console.log(res)},()=>{})
|
手写promise: ES6版
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
| class MyPromise { constructor (executor) { this.state = 'pending' this.value = undefined
this.callbacks = [] const resolve = (value)=> { if (this.state === 'pending') { this.state = 'fulfilled' this.value = value this.callbacks.forEach((handle)=>{ handle.onFulfilled(value) }) } } const reject = (value) => { if(this.state === 'pending') { this.state = 'rejected' this.value = value this.callbacks.forEach((handle)=>{ handle.onRejected(value) }) } } try{ executor(resolve,reject) } catch (e) { reject(e) }
} then (onFulfilled, onRejected) { if (this.state === 'fulfilled') { onFulfilled(this.value) } else if(this.state === 'rejected') { onRejected(this.value) } else { this.callbacks.push({ onFulfilled, onRejected }) console.log(this.callbacks) } } }
const p1 = new MyPromise((resolve, reject)=>{ setTimeout(()=>{ resolve('成功') },2000) }) p1.then((res)=>{console.log(res)},()=>{})
|