-1

i was trying out promise code but it always returns me resolve even if the user does not exist in the database can anyone help me fix my code and the return statement in the return function the the second console log is only working.

here is my code

Api Call

const email = 't@t.com';
const request = require('request');
function IsUserExists(email, kc_accessToken) {
  let url = `${path}/users?email=${email}`;

  return new Promise(function (resolve, reject) {
    request(
      {
        url: url,
        headers: {
          'content-type': 'application/json',
          authorization: `Bearer ${kc_accessToken}`,
        },
      },
      function (error, response, body) {
        if (error) {
          console.log('some error occured');
        }
        if (response.body.length > 0) {
          console.log('User Exist');
          return resolve();
        }
        console.log('Does not Exist');
        return reject();
      }
    );
  });
}

Function Call

http
  .createServer(function Test() {
    getAccessToken()
      .then(function (response) {
        kc_accessToken = response.data.access_token;

        IsUserExists(email, kc_accessToken).then((resp) => {
          if (resp) {
            console.log('Do Not Create');
          } else if (!resp) {
            console.log('Creat a new User');
          }
        });
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .then(function () {
        // always executed
      });
  })
  .listen(8081);

When Provided user email which exist ( t@t.com )

enter image description here

When Provided user email which does not exist( 09@t.com )

enter image description here

felixmosh
  • 32,615
  • 9
  • 69
  • 88
  • What is your data of response.body in `response.body.length > 0`? – Jack Yu Nov 08 '20 at 07:36
  • response.body.length > 0 = true value – shafeen sulaiman Nov 08 '20 at 07:38
  • 1
    It looks like `response.body.length >0` is always true, whether the user exists or not. You need to do your own debugging by logging `console.log(response.body)` in both cases and see what data you actually have. – jfriend00 Nov 08 '20 at 07:39
  • 1
    Also, `return resolve()` will resolve the promise with a value of `undefined` which will not work properly with your code in the `.then()` handler where you do `if(resp) {...}` because `resp` will never be truthy there. You need to change one of them. – jfriend00 Nov 08 '20 at 07:40
  • You try to print the "response.body" when provide existed user and non-existed user. Try to figure out what is the value of "response.body" in both situation. – Jack Yu Nov 08 '20 at 07:41
  • okay thank you. i will but how do i return the resolve return value to the function call? – shafeen sulaiman Nov 08 '20 at 07:41
  • 1
    you should use like `resolve(response.body)` to return the data. – Jack Yu Nov 08 '20 at 07:42
  • You can do `return resolve(true)`, but honestly, you don't need any return value for the logic you show. If the promise resolves, the user exists, if the promise rejects it does not exist so you don't need a resolved value and you don't need to check the resolved value. – jfriend00 Nov 08 '20 at 07:42
  • in the promise returned by `IsUserExists` you use `resolve()` and `reject()` i.e. you resolve/reject undefined ... yet you expect some value in `IsUserExists(email, kc_accessToken).then((resp)` ... resp will ALWAYS be undefined – Jaromanda X Nov 08 '20 at 07:42
  • i tried both ways if there is no user it gives me "[ ]" in the console log and if user exist the details of the user is printed in body[ username, email etc] – shafeen sulaiman Nov 08 '20 at 07:44
  • I saw there are three parameters in the callback. 1.error 2.response 3.body. Try to use `if (body.length > 0)`. And you could print the "console.log(typeof response.body)" to check type. I think it's all "string type" in both situation which existed user and non-existed user. – Jack Yu Nov 08 '20 at 07:50
  • When printing console.log(typeof response.body) gives me String in both cases whether the user exist or not. When Printing (body.length > 0) with user or without it give me true value – shafeen sulaiman Nov 08 '20 at 08:01
  • 1
    Goods sign. Because you treat these data as string so "[]" and "[username etc..]" are length bigger than 0 ("[]".length is 2, "[username etc..]" might might be 10 or higher). You need to use `JSON.parse` to parse your response.body. – Jack Yu Nov 08 '20 at 08:04
  • 1
    Here is an example. `let a = "[]"; console.log(a.length)` will be two, `let a = "[1,2,3]"; console.log(a.length)` will be 7. And after you use JSON.parse `let a = JSON.parse("[]"); console.log(a.length)` will be zero `let a = JSON.parse("[1,2,3]"); console.log(a.length)` will be three – Jack Yu Nov 08 '20 at 08:08
  • yes it works now thank you so much. now i have small question when i give a wrong email it gives me an error telling me unhandled rejection so i want to ask what should i return in "return reject()" – shafeen sulaiman Nov 08 '20 at 08:24
  • I created a new answer because I need use an example. – Jack Yu Nov 08 '20 at 08:35

1 Answers1

1

I need to create a new answer for example to you question in comments.
Now, you go into the reject function so you need to handle this rejection in the outside.

if (response.body.length > 0) {
    console.log('User Exist');
    return resolve();
}
console.log('Does not Exist');
return reject(); // -> Now here you are

You need add .catch function after IsUserExists.then().
It will be IsUserExists.then().catch()

http.createServer(function Test() {
    getAccessToken()
        .then(function (response) {
            kc_accessToken = response.data.access_token;

            // here you only accept the data from resolve in Promise
            // so you need to add .catch function to handle the rejection.
            IsUserExists(email, kc_accessToken).then((resp) => {
                if (resp) {
                    console.log('Do Not Create');
                } else if (!resp) {
                    console.log('Creat a new User');
                }
            }).catch((error) => {
                console.log(error)
            });


        })
        .catch(function (error) {
            // handle error
            console.log(error);
        })
        .then(function () {
            // always executed
        });
})
.listen(8081);

By the way, you could add parameter in rejection function like reject(new Error("user not found)).
Then in the outside, you can get this rejection message.

Jack Yu
  • 2,190
  • 1
  • 8
  • 14
  • good. it works. but there is an issue now what i would like to do is if the user does not exist then i want to go to else if function and do a create user method but in our case it rejects and goes to catch so i dont think i can write my create method inside that – shafeen sulaiman Nov 08 '20 at 08:43
  • 1
    You can use resolve in both situation. If use exist, resolve(true), if use not existed, resolve(false). There are no rejection any more. Then you can get `true` or `false` in the `IsUserExists(email, kc_accessToken).then((resp) => {console.log(resp) // true or false })`. – Jack Yu Nov 08 '20 at 08:46