I’m trying to perform a synchronous loop until a fetch to a URL is successful.
Here’s what I’ve attempted:
let res = null
fetch("https://jsonplaceholder.typicode.com/users/1").then((response)=>{
return response.json();
}).then((data)=>{
res = data;
return data
})
while(!res){
console.log(`${Date.now()} fetching`);
}
However, it doesn’t work because the callback is not executed, leading to res = null.
How can I modify this to perform a synchronous loop until a fetch to a URL is successful?
3
Answers
Hey looks like in the code example you’re misusing the power of Promises.
I have 2 options that can help to make your code work.
Note: Use
const
when possible.Documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
.then
statement:Note: The code out of the function or
.then
block will continue executing and once the response comes back the code inside will too.I hope it works for you!
Best Regards!
I have modified your code. Once try this.
You can’t synchronously wait for an asynchronous function in regular JavaScript.
JavaScript is single-threaded: different pieces of code do not run at the same time. Instead they are scheduled using an event loop. Further, the way the event loop works is that every piece of code will run to completion before picking up the next piece of code off the event queue. So, as you discovered, as your
while
loop cannot complete on its own, the runtime never has a chance to execute the callback:while
just keeps on looping.The good news is, you don’t need to do what you are attempting. Whether you are using the browser or Node.js, the program won’t exit while you are awaiting your
fetch
to complete (and of course, the browser runtime never exits). No waiting loop is needed.Instead, simply add the code to do whatever you want to do with the data in your
then
callback and it will be executed when the data is received.