2

I think I am running into a callback issue as returning the result is saying undefined (despite being shown correctly in the console log).

web3.eth.getBlockNumber(function(error, result){
    if(!error)
    {
        console.log(result)
        return result
    }
    else
    {
        console.error(error);
        alert(error)
    }
})

I'm unable to pass the callback result to another function/variable currently. Please assist. Thanks.

4
  • what problem/error are you having? you appear to be returning the result and not passing it anywhere
    – Shomari
    Commented Jan 1, 2018 at 1:49
  • try alert(result) to see if it pops up correctly
    – thefett
    Commented Jan 1, 2018 at 1:51
  • i'm getting undefined in the console and if i alert it.
    – jack bauer
    Commented Jan 1, 2018 at 1:55
  • have you included web3.js or MetaMask-injected? <script src="https://unpkg.com/[email protected]/src/index.js"></script>
    – Shomari
    Commented Jan 2, 2018 at 2:06

1 Answer 1

1

This is a common point of confusion for new JavaScript developers. If you want to pass result to something else, you need to call another function. E.g.:

web3.eth.getBlockNumber(function (error, result) {
  otherFunction(result);
});

function otherFunction(result) {
  console.log("In otherFunction with: " + result);
}

Currently, you're just returning result, which just means it gets returned to the caller of your callback, which is web3.eth.getBlockNumber (and it isn't expecting a return value from the callback at all, so it ignores it).

2
  • ok, but what's the solution?
    – Dr.X
    Commented Nov 3, 2018 at 17:17
  • I'm not sure what you're asking. My answer includes working code.
    – user19510
    Commented Nov 3, 2018 at 17:18

Your Answer

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

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