不能将 async/await 与 Axios 和 array.map() 一起使用,其中包含 settimeout



我使用的API每秒只允许3次调用,需要进行大量调用。

所以我需要在地图中使用Await Axios的SetTimeout,但我无法实现。

我尝试从promise导入setTimeout,但没有成功。

import { setTimeout } from 'timers/promises';
const apiCall = await Promise.all(data?.map( async item => {

await setTimeout(resolve, 334)

const numeroPedidoBling = item?.numeroPedidoBling;


const orderData = await axios.get(`${BLING_URL}/${numeroPedidoBling}/json?apikey=${APIKEY}`, { headers: {
'Accept': "application/json"
}})

return orderData?.data?.retorno;
}))

我尝试了很多不同的方法,但现在我被这段代码卡住了。

现在,它没有等待api调用,我收到错误429(调用太多(

我该怎么做?

Obs.:334内部SetTimeout为1,01秒

编辑。:我尝试同时实现rateLimit和for wait,但它也给出了错误429,请求太多,遵循代码:

try {
const result = [];
for await (let item of data) {
const numeroPedidoBling = item?.numeroPedidoBling;
const request = rateLimit(axios.create(), { maxRPS: 2 })


const orderData = await request.get(`${BLING_URL}/${numeroPedidoBling}/json?apikey=${APIKEY}`, { headers: {
'Accept': "application/json"
}})
result.push(orderData?.data?.retorno);
}
} catch (error) {
throw Error(error)

}

我通过使用for await和setTimeout成功实现了这一点,因为我需要每秒只进行3次api调用,所以它成功了。

遵循代码:

import { setTimeout } from 'timers/promises';
import axios from 'axios';
const result = [];
let counter = 0;
for await (let item of data) {
counter+=1
const numeroPedidoBling = item?.numeroPedidoBling;
if(counter%3 === 0) {
await setTimeout(1000)
}


const orderData = await axios.get(`${BLING_URL}/${numeroPedidoBling}/json?apikey=${APIKEY}`, { headers: {
'Accept': "application/json"
}})
result.push(orderData?.data?.retorno);
}

用户概念去抖动节流

https://medium.com/nerd-for-tech/debouncing-throttling-in-javascript-d36ace200cea#:~:text=摘要%3A,与%20of%20连续%20用户%20操作无关。

最新更新