简体   繁体   English

在 nodejs 中执行下一次迭代之前等待 API 返回其响应

[英]Wait for API to return its response before executing the next iteration in nodejs

I am new to nodejs.我是 nodejs 的新手。 I have an array of string that consists of around 30000+ values, which has the below format我有一个由大约 30000+ 个值组成的字符串数组,其格式如下

tickerArray = ["A","AA","AAA", ..........., "C"]

I want to loop through these and need to sent each value to an external polygon.io API.我想遍历这些并需要将每个值发送到外部polygon.io API。 But the Polygo.io free plan only allows 5 API Call per minute.但是 Polygo.io 免费计划每分钟只允许 5 个 API 调用。 Below is my code.下面是我的代码。

await tickerArray.reduce((key:any, tickerSymbol:any) =>
    key.then(async () => await stockTickeDetails.runTask(tickerSymbol)),
    starterPromise
    );
}).catch(function (error: any) {
    console.log("Error:" + error);
   });

My runTask function is below :我的 runTask 函数如下:

public  runTask(tickerSymbol:any) {
 return  axios.get('https://api.polygon.io/v1/meta/symbols/' + tickerSymbol + '/company?apiKey=' + process.env.API_KEY).then(
   function (response: any) {
        console.log("Logo : " + response.data.logo + 'TICKER :' + tickerSymbol);
        let logo = response.data.logo;
        let updateLogo =  stockTickers.updateOne({ ticker: tickerSymbol }, { $set: { "logo": logo } })
      }).catch(function (error: any) {
        console.log("Error from symbol service file : " + error);
      });

} }

Here what I need is, if I pass the 0th index value ie, "A" to runTask method, it should process the API and should return the result and from the result I need to update the database collection accordingly.这里我需要的是,如果我将第 0 个索引值(即“A”)传递给 runTask 方法,它应该处理 API 并应该返回结果,并且我需要根据结果相应地更新数据库集合。 Then should go back to the 1code and need to fetch the 1st index value ie "AA" and repeat the process.然后应该回到 1code 并需要获取第一个索引值,即“AA”并重复该过程。

Here after executing 2 APIs I am getting the following error在执行 2 个 API 后,我收到以下错误

Request failed with status code 429. You've exceeded the maximum requests per minute.请求失败,状态码为 429。您已超过每分钟的最大请求数。

I guess this is because it is not waiting till the request to get processed with each value.我想这是因为它不会等到请求处理每个值。 How can I resolve it by adding a set time out which delays 5 API call per minute.如何通过添加每分钟延迟 5 个 API 调用的设置超时来解决它。

You can easily achieve this using Promise pattern, here is your solution:您可以使用 Promise 模式轻松实现这一点,这是您的解决方案:

var tickerArray = ["A","AA","AAA", ..........., "C"]
let requests = tickerArray.map(tickerSymbol => {
   //generate a promise for each API call
   return new Promise((resolve, reject) => {
      request({
         uri: https://api.polygon.io/v1/meta/symbols/' + tickerSymbol + '/company?apiKey=' + process.env.API_KEY,
         method: 'GET'
      },
      (err, res, body) => {
      if (err) { reject(err) }
      //call to resolve method which is passed to the caller                             
      //method passed to the promise
      resolve( { response : body, request: tickerSymbol })
      })
   })
})

Promise.all(requests).then((objArray) => { 
//this is expected when all the promises have been resolved/rejected.
    objArray.forEach(obj => {
        if (obj) {
            console.log("Logo : " + obj.response.data.logo + 'TICKER :' + obj.request);
            let logo = obj.response.data.logo;
            let updateLogo =  stockTickers.updateOne({ ticker: obj.request }, { $set: { "logo": logo } })
        }
    })
}).catch(error => console.log("Error from symbol service file : " + error);)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM