Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rejecting promise when using fetch [duplicate]

I am a bit confused with how to properly use fetch. It seems to resolve even when I get an error status back. Is the below code correct (wrapping the fetch in another promise)?

function a(url, config) {
  if (!config)
    config = {};

  config = Object.assign(config, {
    headers: {
      'content-type': 'application/json;charset=utf-8'
    }
  })
  return new Promise(
    function(resolve, reject) {
      fetch(url, config).then(
        function(res) {
          if (res.status == 200 && res.ok) {
            console.log("Promise resolved")
            resolve(res);
            return;
          }
          console.log("Promise rejected")
          reject(res);
        },
        function(rej) {
          console.log("promise rejected")
          reject(rej);
        }
      )
    }
  )
}

function b() {
  a('/test').then(
    function(res) {
      console.log('success');
      console.log(res)
    },
    function(rej) {
      console.log('Rejected');
      console.log(rej)
    }
  )
}

b();
(The above code should run fine in chrome via console... just copy/paste )
like image 550
Goblinlord Avatar asked Dec 06 '15 10:12

Goblinlord


People also ask

Does fetch () return a Promise?

fetch() starts a request and returns a promise. When the request completes, the promise is resolved with the Response object. If the request fails due to some network problems, the promise is rejected.

What happens if multiple resolve or reject is called within a Promise?

The only thing to understand is that once resolved (or rejected), that is it for a defered object - it is done. If you call then(...) on its promise again, you immediately get the (first) resolved/rejected result. Additional calls to resolve() will not have any effect.

What happens when Promise is rejected?

If the Promise rejects, the second function in your first . then() will get called with the rejected value, and whatever value it returns will become a new resolved Promise which passes into the first function of your second then.


1 Answers

If you want to reject from success callback you need to do it explicitly by either returning rejected promise, e.g. return Promise.reject('error occurred'); or by throwing.

Additionally, you should not abuse Promise constructor in your case since fetch already returns promise object:

function a(url, config) {
    if (!config)
        config = {};

    config = Object.assign(config, {
        headers: {
            'content-type': 'application/json;charset=utf-8'
        }
    });

    return fetch(url, config).then(
        function(res) {
            if (res.status == 200 && res.ok) {
                console.log("Promise resolved")
                return res.json();
            }
            console.log("Promise rejected");
            throw 'promise rejected';
        },
        function(rej) {
            console.log("promise rejected");
            throw 'promise rejected';
        }
    );
}
like image 166
dfsq Avatar answered Oct 12 '22 07:10

dfsq