Skip to content Skip to sidebar Skip to footer

Dealing With Forgotten Promises In Javascript

Here is an example that will hopefully make understaning the question easier. In the script above there is an action (listen) that will enable another action (submit), using the h

Solution 1:

As mentioned in this answer;

Most code that uses promises expects them to resolve or reject at some point in the future (that's why promises are used in the first place). If they don't, then that code generally never gets to finish its work.

It's possible that you could have some other code that finishes the work for that task and the promise is just abandoned without ever doing its thing. There's no internal problem in Javascript if you do it that way, but it is not how promises were designed to work and is generally not how the consumer of promises expect them to work.

Failing to resolve or reject a promise doesn't cause a problem in Javascript, but it's a bad practice anyway. Your application cannot determine what happened to the promise if it never resolves. Instead of leaving the promise in limbo, return a value like an error message, and have the promise filter results for an error message. If it finds an error, reject() the promise so the application can determine its next move.

var listen = document.querySelector("#listen"),
  cancel = document.querySelector("#cancel"),
  submit = document.querySelector("#submit");

var promiseResolve = null;

listen.addEventListener("click", startListening);
cancel.addEventListener("click", onCancelClick);
submit.addEventListener("click", onSubmitClick);
submit.disabled = true;

functionstartListening() {
  submit.disabled = false;
  listen.disabled = true;
  newPromise(function(resolve, reject) {
    promiseResolve = (error) => {
       if (error) { reject(error); } else { resolve(); }
    };
  }).then(onSubmit)
  .catch(error =>onError(error));
}

functionabort() {
  listen.disabled = false;
  submit.disabled = true;
  promiseResolve = null;
}

functiononSubmitClick() {
  if (promiseResolve) promiseResolve();
}

functiononCancelClick() {
  if (promiseResolve) promiseResolve("Cancelled!");
}

functiononSubmit() {
  console.log("Done");
  abort();
}

functiononError(error) {
  console.warn(error);
  abort();
}
<buttonid="listen">Listen</button><buttonid="submit">Submit</button><buttonid="cancel">Cancel</button>

Post a Comment for "Dealing With Forgotten Promises In Javascript"