all的使用
function getJSON(id) { return new Promise((res,rej)=>{ setTimeout(()=>{ res(id) },1000) }) } // 生成一个Promise对象的数组 const promises = [2, 3, 5, 7, 11, 13].map(function (id) { return getJSON('/post/' + id + '.json'); }); console.log(promises); Promise.all(promises) .then(function (posts) { console.log(posts); }) .catch(function (reason) { });
Promise.race()
// race是赛跑的意思,返回的promise对象的状态和结果为数组中第一个执行完的promise的状态和结果 let p = new Promise((resolve, reject) => { setTimeout(() => { resolve('成功') }) }) let p1 = Promise.reject('err') let p2 = Promise.resolve('OK!') let result = Promise.race([p, p1, p2]) console.log(result) // 返回p1的状态和结果
es11新特性(返回所有状态)
Promise.allSettled([ fetch("https://api.github.com/users/pawelgrzybek").then(data => data.json()), fetch("https://api.github.com/users/danjordan").then(data => data.json()) ]) .then(result => console.log(`All profile settled`));
es6封装
class Promise { constructor(executor) { this.PromiseState = 'pending' // 实例对象添加状态属性 this.PromiseResult = null // 实例对象添加结果属性 this.callbacks = [] // 提供一个数组用于保存所有的回调函数 const _this = this // 保存实例对象this的值 // 定义resolve函数 function resolve(data) { if (_this.PromiseState !== 'pending') return // 限制promise的状态只能改变一次 _this.PromiseState = 'fulfilled' // 修改对象的状态 _this.PromiseResult = data // 修改对象的结果 // if(_this.callback.onResolved) _this.callback.onResolved(data) // 为什么在这里调用回调函数而不是在then方法中:异步任务先指定了回调,在状态发生改变时执行回调函数 _this.callbacks.forEach((item) => { item.onResolved(data) }) } // 定义reject函数 function reject(data) { if (_this.PromiseState !== 'pending') return // 限制promise的状态只能改变一次 _this.PromiseState = 'rejected' // 修改对象的状态 _this.PromiseResult = data // 修改对象的结果 // if(_this.callback.onRejected) _this.callback.onRejected(data) // 在这里调用回调函数:异步任务先指定了回调,在状态发生改变时执行回调函数 _this.callbacks.forEach((item) => { item.onRejected(data) }) } // try{}catch(){} 语句处理throw抛出的异常 try { executor(resolve, reject) // 同步调用执行器函数 } catch (err) { reject(err) } } then(onResolved, onRejected) { // 提供异常穿透。如果then()中的第二个参数没有传递,默认抛出onRejected回调 if (typeof onRejected !== 'function') onRejected = (reason) => { throw reason } // 如果第一个参数没有传递,默认执行onResolved()回调 if (typeof onResolved !== 'function') onResolved = (data) => data return new Promise((resolve, reject) => { const callback = (type) => { try { let result = type(this.PromiseResult) if (result instanceof Promise) { result.then( (data) => { resolve(data) }, (err) => { reject(err) } ) } else { resolve(result) } } catch (e) { reject(e) } } if (this.PromiseState === 'fulfilled') { setTimeout(() => { callback(onResolved) }) } else if (this.PromiseState === 'rejected') { setTimeout(() => { callback(onRejected) }) } else if (this.PromiseState === 'pending') { this.callbacks.push({ onResolved: () => { setTimeout(() => { callback(onResolved) }) }, onRejected: () => { setTimeout(() => { callback(onRejected) }) } }) // 保存回调函数 } }) } catch(onRejected) { return this.then(undefined, onRejected) } static resolve(result) { return new Promise((resolve, reject) => { if (result instanceof Promise) { result.then( (data) => { resolve(data) }, (err) => { reject(err) } ) } else { resolve(result) } }) } static reject(err) { return new Promise((resolve, reject) => { reject(err) }) } static all(promiseArr) { return new Promise((resolve, reject) => { let count = 0, list = [] promiseArr.forEach((item, index) => { item.then( (data) => { count++ list[index] = data if (count === promiseArr.length) resolve(list) }, (err) => { reject(err) } ) }) }) } static race(promiseArr) { return new Promise((resolve, reject) => { promiseArr.forEach((item) => { item.then( (data) => { resolve(data) }, (err) => { reject(err) } ) }) }) } }
为promise取消异步事件
const makeCancelable = (promise) => { let hasCanceled_ = false; const wrappedPromise = new Promise((resolve, reject) => { promise.then((val) => hasCanceled_ ? reject({isCanceled: true}) : resolve(val) ); promise.catch((error) => hasCanceled_ ? reject({isCanceled: true}) : reject(error) ); }); return { promise: wrappedPromise, cancel() { hasCanceled_ = true; }, }; }; const somePromise = new Promise(r => setTimeout(r, 1000));//创建一个异步操作 const cancelable = makeCancelable(somePromise);//为异步操作添加可取消的功能 cancelable .promise .then(() => console.log('resolved')) .catch(({isCanceled, ...error}) => console.log('isCanceled', isCanceled)); // 取消异步操作 cancelable.cancel();
使用async处理promise事件
function pp() { return new Promise((res, rej) => { setTimeout(() => { rej('11'); }, 1000); }).catch(err => err); } aa(); async function aa() { const b = await pp(); console.log('11', b); }