What happens if you don't resolve or reject a promise?

JavascriptEcmascript 6Es6 Promise

Javascript Problem Overview


I have a scenario where I am returning a promise. The promise is basically triggered by an ajax request.

On rejecting the promise it shows an error dialog that there is a server error.

What I want to do is when the response code is 401, I neither want to resolve the promise nor reject it (because it already shows the error dialog). I want to simply redirect to the login page.

My code looks something like this:

function makeRequest(ur, params) {
  return new Promise(function (resolve, reject) {
    fetch(url, params).then((response) => {
      let status = response.status;    
      if (status >= 200 && status < 300) {
        response.json().then((data) => {
          resolve(data);
        });
      } else {
        if (status === 401) {
          redirectToLoginPage();
        } else {
          response.json().then((error) => {
            if (!error.message) {
              error.message = constants.SERVER_ERROR;
            }
            reject({ status, error });
          });
        }
      }
    });
  });
}

As you can see, if the status is 401, I am redirecting to the login page. The promise is neither resolved nor rejected.

Is this code OK, or is there any better way to accomplish this?

Javascript Solutions


Solution 1 - Javascript

A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object. The promise will still get garbage collected (even if still pending) if no code keeps a reference to the promise.

The real consequence here is what does that mean to the consumer of the promise if its state is never changed? Any .then() or .catch() listeners for resolve or reject transitions will never get called. 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.

> As you can see if the status is 401, I am redirecting to login page. > Promise is neither resolved nor rejected. > > Is this code OK? Or is there any better way to accomplish this.

In this particular case, it's all OK and a redirect is a somewhat special and unique case. A redirect to a new browser page will completely clear the current page state (including all Javascript state) so it's perfectly fine to take a shortcut with the redirect and just leave other things unresolved. The system will completely reinitialize your Javascript state when the new page starts to load so any promises that were still pending will get cleaned up.

Solution 2 - Javascript

I think the "what happens if we don't resolve reject" has been answered fine - it's your choice whether to add a .then or a .catch.

However, Is this code OK? Or is there any better way to accomplish this. I would say there are two things:

You are wrapping a Promise in new Promise when it is not necessary and the fetch call can fail, you should act on that so that your calling method doesn't sit and wait for a Promise which will never be resolved.

Here's an example (I think this should work for your business logic, not 100% sure):

const constants = {
  SERVER_ERROR: "500 Server Error"
};
function makeRequest(url,params) {
  // fetch already returns a Promise itself
  return fetch(url,params)
        .then((response) => {

            let status = response.status;
            
            // If status is forbidden, redirect to Login & return nothing,
            // indicating the end of the Promise chain
            if(status === 401) {
              redirectToLoginPage();
              return;
            }
            // If status is success, return a JSON Promise
            if(status >= 200 && status < 300) {
              return response.json();
            }
            // If status is a failure, get the JSON Promise,
            // map the message & status, then Reject the promise
            return response.json()
              .then(json => {
                if (!json.message) {
                    json.message = constants.SERVER_ERROR;
                }
                return Promise.reject({status, error: json.message});
              })
        });
}
// This can now be used as:
makeRequest("http://example", {})
  .then(json => {
    if(typeof json === "undefined") {
      // Redirect request occurred
    }
    console.log("Success:", json);
  })
  .catch(error => {
    console.log("Error:", error.status, error.message);
  })

By contrast, calling your code using:

makeRequest("http://example", {})
  .then(info => console.log("info", info))
  .catch(err => console.log("error", err));

Will not log anything because the call to http://example will fail, but the catch handler will never execute.

Solution 3 - Javascript

As others stated it's true that it's not really an issue if you don't resolve/reject a promise. Anyway I would solve your problem a bit different:

function makeRequest(ur,params) {

    return new Promise(function(resolve,reject) {

        fetch(url,params)
        .then((response) => {

            let status = response.status;

            if (status >= 200 && status < 300) {
                response.json().then((data) => {
                    resolve(data);
                })
            }
            else {
                reject(response);
            }
        })
    });
}

makeRequest().then(function success(data) {
   //...
}, function error(response) {
    if (response.status === 401) {
        redirectToLoginPage();
    }
    else {
        response.json().then((error) => {
            if (!error.message) {
                error.message = constants.SERVER_ERROR;
            }
            
            //do sth. with error
        });
    } 
});

That means I would reject every bad response state and then handle this in your error handler of your makeRequest.

Solution 4 - Javascript

It works and isn't really a problem, except when a caller of makeRequest expects of promise to fulfil. So, you're breaking the contract there.

Instead, you could defer the promise, or (in this case) reject with status code/error.

Solution 5 - Javascript

The ECMAScript spec explains the purpose of promises and new Promise():

> A Promise is an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation. > > 25.6.3.1 Promise ( executor ) > > NOTE The executor argument must be a function object. It is called for initiating and reporting completion of the possibly deferred action represented by this Promise object.

You should use promises to obtain future values. Furthermore, to keep your code concise and direct, you should only use promises to obtain future values, and not to do other things.

Since you’ve also mixed program control flow (redirection logic) into your promise’s “executor” logic, your promise is no longer “a placeholder for the results of a computation;” rather, it’s now a little JavaScript program masquerading as a promise.

So, instead of wrapping this JavaScript program inside a new Promise(), I recommend just writing it like a normal JavaScript program:

async function makeRequest(url, params) {
  let response = await fetch(url, params);
  let { status } = response;
  if (status >= 200 && status < 300) {
    let data = await response.json();
    successLogic(data);
  } else if (status === 401) {
    redirectToLoginPage();
  } else {
    let error = await response.json()
    if (!error.message) {
      error.message = constants.SERVER_ERROR;
    }
    errorLogic({ status, error });
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAniketView Question on Stackoverflow
Solution 1 - Javascriptjfriend00View Answer on Stackoverflow
Solution 2 - JavascriptCodingIntrigueView Answer on Stackoverflow
Solution 3 - JavascriptFidel90View Answer on Stackoverflow
Solution 4 - JavascriptnullpotentView Answer on Stackoverflow
Solution 5 - JavascriptJacksonView Answer on Stackoverflow