We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
promise的地位不言而喻,凡是需要异步处理的现在基本都在使用promise; promise的出现解决了异步处理中回调地狱的问题,使得开发者可以使用同步的方式去写异步逻辑。开发体验得到极大的提升;同时Promise还提供了很多有用的工具函数。 这里着重说一下Promise.all方法;
promise
Promise.all
Promise.all实现将多个Promise实例包装成一个的功能。
Promise
Promise.resolve
reslove
function PromiseAll(promises = []) { return new Promise((resolve, reject) => { if (!Array.isArray(promises)) { reject('PromiseAll 参数必须为数组') } let resloveNum = 0 //记录reslove的个数 const promisesLength = promises.length const result = [] promises.forEach((item, index) => { let actionItem = item // 如果不是promise实例,使用Promise.resolve转换成 Promise 实例 if (!(item instanceof Promise)) { actionItem = Promise.resolve(item) } actionItem.then(res => { resloveNum++; result[index] = res //确保返回顺序和参数顺序一致 if (resloveNum === promisesLength) { resolve(result) } }).catch(res => { reject(res) }) }) }) }
const p1 = new Promise((resolve, reject) => { setTimeout(() => { resolve(1) }, 1000) }) const p2 = 2 const p3 = Promise.resolve(3) const p4 = Promise.reject(4) PromiseAll([p1, p2, p3]).then((res) => { console.log('resolve',res) }).catch(res => { console.log('catch', res) }) // 1秒后输出 resolve [1,2,3] PromiseAll([p2, p3, p4]).then((res) => { console.log('resolve', res) }).catch(res => { console.log('catch', res) }) // 输出 catch 4
The text was updated successfully, but these errors were encountered:
No branches or pull requests
简介
promise
的地位不言而喻,凡是需要异步处理的现在基本都在使用promise
;promise
的出现解决了异步处理中回调地狱的问题,使得开发者可以使用同步的方式去写异步逻辑。开发体验得到极大的提升;同时Promise还提供了很多有用的工具函数。 这里着重说一下Promise.all
方法;功能
Promise.all
实现将多个Promise
实例包装成一个的功能。Promise
实例,如果不是,内部会用Promise.resolve
转化。Promise
都reslove
时,Promise.all
才reslove
。且返回的顺序和参数顺序一致(可以保证多个异步任务返回的顺序),其中一个失败时,整体失败,返回失败的那个实例数据。简单实现
测试
The text was updated successfully, but these errors were encountered: