将 setInterval() 与数组中的 .map 方法一起使用并作为承诺返回 [英] Using setInterval() with a .map method in array and returning as a promise

查看:25
本文介绍了将 setInterval() 与数组中的 .map 方法一起使用并作为承诺返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,它接受一个 ID 列表,将它们转换成一个数组 URL,然后使用 map 函数来触发一个获取请求.它工作得很好,但它触发得太快,并且提供程序抛出错误,因为我们太频繁地访问 API.我需要为请求设置一个间隔,但每次我这样做时,它都不起作用.想法?

I have a function that takes a list of IDs, converts them into an array URLS, then uses the map function to fire a fetch request. It works great but it fires too fast and the provider throws errors because we hit the API too often. I need to set an interval for the request but everytime I do, it doesn't really work. Ideas?

async function getReports(reportIDs) {
    const urls = reportIDs.map(id => `https://api.data.com/api/v1/report/${id}/?include_datasets=true`);
    const requests = urls.map(url => fetch(url, {
        method: 'GET',
        headers: { 'api-key': key }
    }).then(res => res.json()));
    
    const responses = await Promise.all(requests).catch(err => console.error(err));
    return responses;
}

我使用了一个 promise,所以我可以在另一个函数中等待函数的结果来转换数据集.

I use a promise so I can await the results of the function inside another function to transform the datasets.

想法?

推荐答案

如果是 node,有一个相当轻量级的 npm 包,叫做 瓶颈 将限制请求.它工作得很好并且被广泛使用.或者你可以看看那个然后自己动手.

If node, there is a fairly lightweight npm package called bottleneck which will throttle requests. It works quite well and is widely used. Or you can look at that and roll your own.

这篇关于将 setInterval() 与数组中的 .map 方法一起使用并作为承诺返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆