constparallelRun = async max => { const requestSliceList = []; for (let i = 0; i < requestList.length; i += max) { requestSliceList.push(requestList.slice(i, i + max)); }
for (let i = 0; i < requestSliceList.length; i++) { const group = requestSliceList[i]; try { const res = awaitPromise.all(group.map(fn =>fn())); console.log('接口返回值为:', res); } catch (error) { console.error(error); } } };
但是如果中间有一次请求失败了 Promise.all就失败了。不需要判断返回值的情况可行。
2.Promise.allSettled
constparallelRun = async max => { const requestSliceList = []; for (let i = 0; i < requestList.length; i += max) { requestSliceList.push(requestList.slice(i, i + max)); }
for (let i = 0; i < requestSliceList.length; i++) { const group = requestSliceList[i]; try { // 使用 allSettled 替换 all const res = awaitPromise.allSettled(group.map(fn =>fn())); console.log('接口返回值为:', res); } catch (error) { console.error(error); } } };