我正在使用 node 和 axios(使用 TS,但这不太重要)来查询 API。我有一套脚本可以调用不同的端点并记录数据(有时过滤数据)。这些脚本用于调试目的。我试图通过在请求之间添加延迟来使这些脚本“更好”,这样我就不会“破坏”API,尤其是当我有一个大数组要传递时。所以基本上我希望它发出 GET 请求并在发出下一个请求之前暂停一定时间。
我尝试过 setTimeout()
函数,但我只是将它们放在请求执行后添加延迟的地方;我插入函数的所有地方都有这个结果。我明白为什么我会得到这个结果,我只需要尽我所能至少增加我对事物运作方式的理解。
虽然我考虑过尝试设置队列或尝试使用拦截器,但我认为我可能“偏离”了具有这些想法的更简单的解决方案。
此外,我还有另一个“基本脚本”,我用 for
循环而不是 map ()
函数和 promise.all
。我也尝试过在该脚本中设置延迟,但没有任何帮助。
var axios = require('axios');
var fs = require('fs');
const Ids = [arrayOfIds];
try {
// Promise All takes an array of promises
Promise.all(Ids.map(id => {
// Return each request as its individual promise
return axios
.get(URL + 'endPoint/' + id, config)
}))
.then((vals) =>{
// Vals is the array of data from the resolved promise all
fs.appendFileSync(`${__dirname}/*responseOutput.txt`,
vals.map((v) => {
return `${JSON.stringify(v.data)} \n \r`
}).toString())
}).catch((e) => console.log)
} catch (err) {
console.log(err);
}
以上代码没有错误;只是不知道如何正确地设置延迟。
最佳答案
你可以试试 Promise.map
来自 bluebird
它有设置concurrency
var axios = require('axios');
var fs = require('fs');
var Promise = require('bluebird');
const Ids = [arrayOfIds];
let concurrency = 3; // only maximum 3 HTTP request will run concurrently
try {
Promise.map(Ids, id => {
console.log(`starting request`, id);
return axios.get(URL + 'endPoint/' + id, config)
}, { concurrency })
.then(vals => {
console.log({vals});
})
;
} catch (err) {
console.log(err);
}
关于javascript - 在 map() 函数中为 axios 请求设置延迟/超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56997860/