skip to Main Content

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


  1. 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.

    1. Leverage the power of async/await syntax:
    async function letsRock() {
       try {
          const res = await fetch("https://jsonplaceholder.typicode.com/users/1")
          // The rest of your code ...
        
          return res // Return the response (Optional)
    
       } catch(e) {
         // Code in case that the request fails
       }
    }
    
    

    Note: Use const when possible.

    Documentation:
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

    1. Write your code inside the .then statement:
    fetch("https://jsonplaceholder.typicode.com/users/1").then((response)=>{
      return response.json();
    }).then((data)=>{
      // Use your data here this block defines that the function already was executed successfully 
    })
    

    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!

    Login or Signup to reply.
  2. I have modified your code. Once try this.

    let res = null;
    async function fetchData() {
        while(!res) {
            await fetch(url)
                  .then((response)=>{
                       return response.json();
                   }).then((data)=>{
                       res = data;
                   })
        }
    }
    
    fetchData();
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search