0

Have been doing quite a bit of work with this RPC API as of late, and am having some major trouble with updating variables from within them. I am quite new to js, and have been doing this like a newbie for too long.Would anyone be willing to show me how these should be worked with?

let x = '';
rpc.api.getConfig(function(err, resp) {
    console.log(err, resp);
    x = result;
});
console.log(x); //COMES UP EMPTY :(

Though if I set a timeout on the log, it will show after a few seconds. I know this is because I do not receive the response right away, but am having major trouble turning this into a promise, or any other solution I can think of lol.

Would greatly appreciate your help.

TylerDurden
  • 39
  • 1
  • 7
  • Everything that depends on the result of an async call needs to be in the callback function. – Barmar Nov 06 '18 at 04:27
  • Man don't you realise how useless it is to mark this. If I could have solved it from the other post, or any of the other 30 I read I would have. I can't apply those situations to this one.. **can you?** – TylerDurden Nov 06 '18 at 04:42
  • 1
    I've reopened, but I'm not sure what you expect. You're calling an asynchronous function, you can't use the returned data before it completes. – Barmar Nov 06 '18 at 04:47
  • See also https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – Barmar Nov 06 '18 at 04:47
  • 1
    Honestly, if this is what a pro would do in the same situation, then theres no need to keep this open @barmar because I know how to use callbacks, I just thought there would be a more efficient way. Thank you though, I am glad to hear I am not doing anything wrong at least. :D – TylerDurden Nov 06 '18 at 04:54
  • 1
    @TylerDurden What, specifically, do you find inefficient about using callbacks? Also, have you heard of `await`? – Brad Nov 06 '18 at 05:04
  • There are examples in https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call?noredirect=1&lq=1 that show how to convert ordinary async code to return promises, and then you can use `async/await` to avoid having to write callbacks. – Barmar Nov 06 '18 at 05:12
  • `am having major trouble turning this into a promise` [this answer](https://stackoverflow.com/a/28057246/1541563) on the duplicate target addresses exactly that. – Patrick Roberts Nov 06 '18 at 05:12
  • https://stackoverflow.com/a/53033950/7865621 This may give some idea about the asynchronous behavior . – Janith Udara Nov 06 '18 at 05:17

1 Answers1

1

Solution of X is undefined due to you console first and then you got the res.

let x = '';
rpc.api.getConfig(function(err, resp) {
  console.log(err, resp);
  x = result;
  console.log(x);
});
Sachin Shah
  • 4,503
  • 3
  • 23
  • 50