0

I'm working on an app where I need to .map() over some wallets, and in the process use the wallet data to make a fetch call, then return a new object with the original wallet data spread into it and finally add the new information from the fetch. (Getting a balance from https://btc1.trezor.io/api/v2/xpub/{my-btc-xpub})

I am running into an issue where .map() hits the fetch calls so fast, that it causes it to fail on the 2nd item.

I've found just placing the fetch in the a setInterval() with 1000 ms is plenty of time for it to fetch repeatedly.

However, setInterval() with 500ms is reproducing the same 503 error my .map() fetch()es have been returning to me.

All of my code works until I've added a second wallet to my database, causing the map to run at least twice.

Is there a way to regulate how fast these fetch()es will be made? Is there a better way of going about this problem?

Related working code:

setInterval(() => {
    fetch(`https://btc1.trezor.io/api/v2/xpub/${xpub}`)
        .then(response => response.json())
        .then(data => console.log(data))
}, 1000)

Related broken code:

    static async getWalletBalances(_accountsList) {
        try {
            let accountPromises = _accountsList.map(async account => {
                let walletPromises = account.wallets.map(async wallet => {
                    //breaks right here!!!
                    let balance = await fetch(`https://btc1.trezor.io/api/v2/xpub/${wallet.walletXpub}`)
                         /*
                         this response becomes a 503 html page response instead of json
                         after the first wallet data is fetched
                         */
                        .then(response => response.json())
                        .then(data => data.balance)
                    return { ...wallet, balance: balance }

                })

                let wallets = await Promise.all(walletPromises)
                return { ...account, wallets: wallets }
            })

            let accountsList = await Promise.all(accountPromises);
            return accountsList

        } catch (error) {
            console.log(`Unable to fetch balances: ${error}`)
        }
    }
Phil
  • 157,677
  • 23
  • 242
  • 245
Yintii
  • 43
  • 11
  • 1
    This isn't your problem but the API should really be responding with a [429](https://http.cat/429) if you're exceeding the rate limit. If you can communicate that back to them, it would make the response easier to deal with for you and others – Phil Jul 06 '22 at 03:32
  • using `for` loops instead of `.map` will make this code simple - and if you'd rather mutate the passed in `_accountsList` rather than returning a new `accountsList` it's even simpler – Jaromanda X Jul 06 '22 at 03:41

0 Answers0