1
export const checkLoggedIn = () => {
  return new Promise((resolve, reject) => {
    apiConfig.fetchApi('/users/is_valid', {}, 'get', {})
    .then((resp)=> {
        resolve(true);
    })
    .catch((exception)=> {
        reject(false);
    })
    .done()
  })
}

Above is my user token checking code. But function checkLoggedIn() is giving like the below image enter image description here

But I want to get true or false only. Please if you find the issue in code, comment it out

Andru
  • 5,954
  • 3
  • 39
  • 56
Kumar KS
  • 873
  • 10
  • 21
  • 1
    just return the result of fetchApi and ur done – amd Jun 18 '17 at 18:36
  • 1
    Wrapping an existing promise inside another promise is considered a [promise anti-pattern](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns) as it is totally unnecessary. – jfriend00 Jun 18 '17 at 19:23
  • 1
    Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jun 18 '17 at 21:34

1 Answers1

3

Please check the definitions of then and catch and the general definition and usage of a Promise.

It seems that in your example apiConfig.fetchApi returns a Promise (because you're using then() which works on a Promise). Thus you don't have to create a new Promise.

Your code could look like this (I excluded the response parameter here because you don't use it in your code snippet):

export const checkLoggedIn = () => (
  apiConfig.fetchApi('/users/is_valid', {}, 'get', {})
    .then(() => true)
    .catch(error => { console.log(error); return false; })
);

If apiConfig.fetchApi does not return a Promise, you can create a Promise. But then you have to work with the return value of apiConfig.fetchApi and resolve or reject depending on its value.

Andru
  • 5,954
  • 3
  • 39
  • 56
  • That `catch` callback will never execute. – Bergi Jun 18 '17 at 21:35
  • Of course it could. Promise rejection is handled with `then`, but in case there's any error (network, invalid url, etc.) an error might be thrown and catched with `catch`. – Andru Jun 18 '17 at 22:48
  • 1
    An error *is* a rejection? It will be handled by the second `then` argument before ever reaching the `catch`, and none of your `then` callbacks can throw. – Bergi Jun 18 '17 at 22:52
  • @Bergi Ah, sorry.. I got a bit confused right now.. You're right. Any thrown error should lead to a Promise rejection which would be catched with my `then()` call. I'll remove the reject part from `then`, so that my code is closer to the question. – Andru Jun 18 '17 at 23:04