1

It seems that for a lot of these functions in web3js 1.0.0 there's no reason for it to not return a value or JS object, rather than a promise object.

For example in a previous version of web3js (0.2x.x) the getBalance() function returns:

A BigNumber instance of the current balance for the given address in wei.

But in v1.0.0 if returns:

Promise returns String - The current balance for the given address in wei.

Why the Promise in this case?

It makes it more difficult to work with the functions to interact with websites in my opinion so I am wondering if there is a reasoning for this added complexity.

Thanks to anyone that can help.

1 Answer 1

2

Because the response time depends on the provider, so it doesn't necessarily get the balance straight away. If you want things to behave in a synchronous way, then look into async/await.

But you have to be sure you don't want anything to happen in your app while it's waiting for the balance to be returned. It probably doesn't sound like much, just waiting for the balance, but it really adds up if you're querying multiple things.

EDIT:

As to why they switched, from the 0.2x.x docs:

As this API is designed to work with a local RPC node, all its functions use synchronous HTTP requests by default.

It was from a time when it was assumed everyone would be running a local RPC node, so there was no reason to expect a delay between the function call and the response. Now we're living in a different ecosystem, with services like Infura, so they've updated the library accordingly.

3
  • 1
    Your answer doesn't explain why it has changed between web3 v0.2x.x and web3 v1.0.0, as specified in the question. Obviously, the execution of getBalance on the provider side has not changed (otherwise one of the web3 versions will likely fail to handle this function correctly). Implicitly, the reader might be able to understand that web3 v1.0.0 gives you better flexibility (to choose between synchronous and asynchronous execution). But it might be worth to explain that explicitly. Jul 19, 2018 at 18:39
  • 2
    @goodvibration , answer updated to include the information you requested. Jul 20, 2018 at 12:55
  • 1
    It's a very good question and a very good answer. Jul 20, 2018 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.