Home > Net >  Check, if promise is fulfilled
Check, if promise is fulfilled

Time:01-16

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?

CodePudding user response:

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.

  • Related