Web3.js Multiple Requests – Best Practices for Dependent Requests

batchjavascripttokensweb3js

Looking to get some advice on a pretty common scenario using Web3.js

Let's say you want to calculate the number of tokens for a specific ERC20 token contract that are present at an Ethereum Address.

To do this accurately, you will need to fetch both the balanceOf() and the decimals() values through Web3.js, and then adjust the balance to give a final value.

However, best practice for these Web3 requests is to make sure they are asynchronous, so we may get back the balance at a different time we get back the decimals.

What is the best way to display the adjusted value after both of these values are returned?

From my brief research, you can:

  • Use JavaScript Promises
  • Use Web3.js Batch
  • Nest the Asynchronous Calls

Are there any other options? Is there a best choice from the options above? Or is it scenario driven?

Best Answer

As you mentioned, I think the choice is scenario-based. Specifically, how complex your requests are and how many asynchronous calls you need to make.

Other things to consider are (1) your familiarity with the alternatives, (2) what you're using for asynchronous calls in the rest of your code base - good to have consistency, and (3) your team's familiarity with the method.

I'll throw another one in there that you didn't include on your list:

  • ES8 async/await (although I'd stay this more stylistic: simpler, more concise way of coding promises/chains)

In your example, where there are only two variables you're retrieving, this is pretty simple so you're probably fine using callback / nesting your asynchronous calls. However, the more variables or asynchronous requests you have, this will start getting messy pretty quickly ("callback hell"), not to mention it may take longer to resolve your full chain since each sequential call waits until the previous call resolves until initiating.

So once you have more asynchronous calls, you can benefit from promises due to (1) cleaner syntax, and (2) concurrency by using Promise.all.

Related Topic