this post was submitted on 07 Jul 2023
3 points (100.0% liked)
JavaScript
1700 readers
42 users here now
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
Everything that uses
out2
must be scoped in that function where theconsole.log
is. That's because JavaScript is asynchronous: when that entire code block runs, all it does is "queue" the HTTP request to be done, and then continues running your code before the request has even been made. All it knows is that whenever it's done with the HTTP request, it will call the two functions passed in in thethen
calls, or if it failed, it'll run the function passed into thecatch
call.So the code that does whatever with the result must be a separate function to run maybe later when the request completes. Otherwise, this would just freeze the browser or server until it finishes, and it can't do anything else in the meantime!
If you want a more procedural style, you can use async functions and await in it. For example:
The same can also be written as this:
These two examples are just additional syntax sugar to do the same as with the Promise API in your original code. Internally it splits the code into the same sort of nested functions, but it's easier to read and manage especially if you need to wait on many things.
Of course you need to be in an async context for that: