Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check, if promise is fulfilled

I have sync function with fetch and setInterval, that checks result every second. In console it looks:

Promise {<pending>}
Promise {<pending>}
Promise {<fulfilled>: Response}
Promise {<fulfilled>: Response}
Promise {<fulfilled>: Response}

I need a function that do something till server responds. If it responds, function ends, so i need some check like (getted === fulfilled). How can I do it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the .then() method on the promise returned by the fetch() function to execute a callback function when the promise is fulfilled. In this callback function, you can check the value of the getted variable and if it is equal to "fulfilled", you can end the function.

Here’s an example:

function syncWithServer() {
  let getted = "pending";
  fetch("your_url_here")
    .then(response => {
      if (response.ok) {
        getted = "fulfilled";
        // Do something with the response
      }
      if(getted === "fulfilled"){
        clearInterval(intervalId)
      }
    })
    .catch(error => {
      console.log(error);
    });
  var intervalId = setInterval(syncWithServer, 1000);
}

You can also make use of async/await like this:

async function syncWithServer() {
  let getted = "pending";
  try {
    const response = await fetch("your_url_here");
    if (response.ok) {
      getted = "fulfilled";
      // Do something with the response
    }
  } catch (error) {
    console.log(error);
  }
  if (getted === "fulfilled") {
    clearInterval(intervalId);
  }
  var intervalId = setInterval(syncWithServer, 1000);
}

In this case, you don’t need to use the then() and catch() methods.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading