我使用Promise.all同时处理多个promise ,但我还需要 for each 已解析的promise 运行一个函数.我面临的问题是,如果我将函数直接传递给Promise的.Then(),它将立即执行,而不是等待Promise.all触发它.如何在仍在使用Promise.All的同时 for each 已解析的promise 执行函数?我还需要了解这项计划的进展情况.

async function fetchData(url) {
/***
I want to append a callbackResolve for this fetch, 
but if I use .then() it execute the function and not the Promise.all
**/

  return await fetch(url);
}

const urls = [
  'https://api.example.com/data1',
  'https://api.example.com/data2',
  'https://api.example.com/data3'
];


Promise.all(urls.map(fetchData))

推荐答案

如果所有promise 都实现,则Promise.all返回一个promise ,该promise 使用一组值进行解析--原始promise 的解析值.因此,您只需迭代该数组并对其执行额外的逻辑.

就像这样:

function fetchData(url) {
  return fetch(url);
}

const urls = [
  'https://api.example.com/data1',
  'https://api.example.com/data2',
  'https://api.example.com/data3'
];

const promises = urls.map(fetchData);
Promise.all(promises).then(arr => {
    arr.forEach(callbackResolve);
});

为了监控进度,您可以对最初的promise 使用单独的.then()个呼叫.例如,按如下方式完成上面的代码:

function fetchData(url) {
  return fetch(url);
}

const urls = [
  'https://api.example.com/data1',
  'https://api.example.com/data2',
  'https://api.example.com/data3'
];

const promises = urls.map(fetchData);

let resolveProgress = 0;
for (const promise of promises) {
    promise.then(() => {
        resolveProgres++;
        console.log("Progress:", 
                    ((resolveProgress / promises.length) * 100).toFixed(2) + "%"
                   );
    });
}

Promise.all(promises).then(arr => {
    arr.forEach(callbackResolve);
});

Javascript相关问答推荐

Regex可以 Select 以任何顺序匹配组

Math.random超出了最大调用堆栈

将音频记录从js发送到activx-web服务器以保存到磁盘

如何从defineExpose访问数据和方法

Angular 拦截器错误处理删除方法问题

RxJS setTimeout操作符等效

*ngFor和@代表输入decorator 和选角闭合

深嵌套的ng-container元素仍然可以在Angular 布局组件中正确渲染内容吗?

了解Node.js中的EventEums和浏览器中的addEventEums之间的关系

. NET中Unix时间转换为日期时间的奇怪行为

当作为表达式调用时,如何解析方法decorator 的签名?

从Node JS将对象数组中的数据插入Postgres表

数字时钟在JavaScript中不动态更新

查找最长的子序列-无法重置数组

如何从网站www.example.com获取表与Cheerio谷歌应用程序脚本

加载背景图像时同步旋转不显示的问题

如何在ASP.NET JavaScript中使用Google Charts API仅对绘制为负方向的条形图移动堆叠条形图标签位置

ChartJs未呈现

是否可以在Photoshop CC中zoom 路径项?

React Refs不与高阶组件(HOC)中的动态生成组件一起工作