Home > Blockchain >  How to fetch data from multiple API's at the same time - that require a different seaarch prase
How to fetch data from multiple API's at the same time - that require a different seaarch prase

Time:05-18

I'm making an app that fetches data from 2 different API's at the sane time based on user's search.

The app is supposed to fetch current crypto prices, and historical data. But the API's use 2 different formats for the symbol, like so:

1.

  • BTC-USD (yahoo.com/BTC-USD)
  • BITCOIN (coingecko.com/api/BITCOIN)

if someone looks up 'BITCOIN' its only going to pull up data from 1 api, because the other 1 requires 'BTC-USD'

2.

  • ETH-USD (yahoo.com/ETH-USD)
  • ETHEREUM coingecko.com/api/ETHEREUM

Is it possible to somehow fetch data from both API's at the same time based?

I guess I could see some solutions (hardcoding the data, or switching API's so they use thw same format), altho this path seems pretty work intensive.

Any ideas on how this can be done?

CodePudding user response:

Use Promise.all if you want fetch data from 2 different API's at the sane time:

const fetchData = async (yahoo_API_URL, coingecko_API_URL) => {
    const fetchYahoo = fetch(yahoo_API_URL, /* config */)
    const fetchCoingecko = fetch(coingecko_API_URL, /* config */)
    const [fetchYahooRes, fetchCoingeckoRes] = await Promise.all([fetchYahoo, fetchCoingecko])
    const [cryptoPriceFromYahoo, cryptoPriceFromCoingecko] = await Promise.all([fetchYahooRes.json(), fetchCoingeckoRes.json()])
    ...
  }

  fetchData('yahoo.com/BTC-USD', 'coingecko.com/api/BITCOIN')
  fetchData('yahoo.com/ETH-USD', 'coingecko.com/api/ETHEREUM')
  • Related