我在Nodejs项目中使用Request包以及 Node V.8.x 中引入的 Async / Await 功能来使用第三方API,一切都很好,直到我遇到API提供商的限制;每秒限制10个并发请求的人。
我尝试了许多可用的NPM软件包,例如速率限制器等,但最近发现article与我的问题相关,它向我介绍了qrate软件包。
我尝试使用以下代码处理此问题:可能我需要使用Callback而不是'done'并在我的'fetchAPIDetails'中处理它 - 非常感谢任何帮助。提前谢谢。
const async = require('async')
const request = require('request-promise')
const qrate = require('qrate')
const q = qrate(worker,1,5)
const worker = async (reqBody, options, done) => {
const options = { method: 'POST', url: apiURL, body: reqBody, timeout: 5000}
try{
const response = await request(options)
if(response.error){errorHandler(response.error); return {}}
else {
const body = response.body // Expecting XML
console.log(body.toString().slice(200,350))
return body
}
return done
}
catch(err){return errorHandler(err)} //errorHandler fn
}
const fetchAPIDetails = async () => {
const IdArr = [a,b,c] // An array of id, which need to pass in reqBody
try{
async.eachLimit(IdArr, 1, async id => {
const reqBody = await queryBuilder(id) // queryBuilder fn
q.push(reqBody)
})
} catch(err){return errorHandler(err)} //errorHandler fn
}
答案 0 :(得分:1)
Thank you everyone, who would have worked on my issue here. However, from my further research I get to know, the concurrency of API requests can be handled directly using NPM-Request package, following this article.
Here is my code for reference, for anyone who would like achieve the same:
const request = require('request-promise')
const Parallel = require('async-parallel')
const queryBuilder = async () => { ... } // Builds my Query body (reqBody)
const errorHandler = async (error) => { ... } // Handles Error
const requestHandler = async () => {
try{
const response = await request(options)
console.log(response.toString().slice(200,350))
return response
} catch(err){return errorHandler(err)} //errorHandler fn
}
const fetchAPIDetails = async () => {
const IdArr = [a,b,c] // An array of id, which need to pass in reqBody
Parallel.concurrency = 1
try{
Parallel.each(IdArr, async id => {
const reqBody = await queryBuilder(id) // queryBuilder fn
})
} catch(err){return errorHandler(err)} //errorHandler fn
}