PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 14, 2022

[FIXED] How can I make Axios try with multiple urls and if one of them working then return data

 October 14, 2022     axios, javascript, node.js, youtube-api     No comments   

Issue

Like the title, I'm working on an app that calls the YouTube APIs but sometimes my app makes too many requests that trigger the API quotas limit and thus making the app stop working due to error on the API server. The solution for this which I found on the Internet is to create multiple API keys and looping through them. But I'm having a headache figuring out how to make my Axios trying multiple API URLs before returning the data. Any tips or tricks on this?

Here is the sample code I tried:

async function getYoutubeVideoSnippet(id) {
  const response = await axios.all([
    axios.get(
      "https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=" +
        id +
        "&key=API_KEY"
    ),
    axios.get(
      "https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=" +
        id +
        "&key=API_KEY"
    ),
  ]);
  return response.data;
}


Solution

I don't understand exactly what you want to do, but If you want to have many requests and only need one response, You can use Promise.any. For example

async function fetchData () {
   const requests = [
     axios.get('...'),
     axios.get('...'),
   ]
   const response = await Promise.any(requests)
   return response.data
}

With this example, You can receive the first response, but you should be aware that all requests are eventually sent



Answered By - Ali Jarkani
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing