0

I was trying out the promise function for the REST API instead of using axios method. so I can wait for the result and if there is any error. can anyone help me change this code to promise in node.js so I can do a fetch using promise method. thank you

this is my code

const email = "xxx@xxxx.com"
function isUserExists(email, kc_accessToken) {
    let url = `${path}/users?email=${email}`;
    return axios_instance.get(url,
        {
            headers: {
                "content-type": "application/json",
                "authorization": `Bearer ${kc_accessToken}`
            }
        }).then(function (response) {
            if (response.data.length > 0) {
                return true;
            } else {
                return false;
            }
        })
        .catch(function (error) {
            console.log("some error occured");
        });
}


Method call

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


        IsUserExists(email, kc_accessToken).then((resp) => {
            console.log(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);
  • You already are using promises in that code. What exactly is the problem, what does not work? – Bergi Nov 05 '20 at 14:15

1 Answers1

1

I think you need something like that :

const email = "xxx@xxxx.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.data.length > 0) {
                return resolve();
            }

            return reject();

        });
    });
}
  • Thank you so much. but i have an error at resposne.data.length it says length is undefined is it the problem with promise function because in other method it was working fine – shafeen sulaiman Nov 05 '20 at 14:37
  • I think you need to investigate what is placed inside your `response` object. Can you add console.log(response) and check if `data` is placed there? Also there might will need to add JSON.parse(response).data.length – Sergey Bondarenko Nov 05 '20 at 14:44
  • sure i will look into it. i did try and it gave me SyntaxError: Unexpected token o in JSON at position 1 – shafeen sulaiman Nov 05 '20 at 14:59
  • then you need to check what the `response` object structure, just place console.log(response) before calling `response.data.length`. – Sergey Bondarenko Nov 05 '20 at 15:04
  • body: '[{"id":"8332caed-2311-4b9d-8c27-f603a6992170","createdTimestamp"}] this is what i get as a result its printing in this form. what i am actually trying to do was find if there is any email or user in that list and then return true – shafeen sulaiman Nov 05 '20 at 15:06
  • according to your `response` object structure : `if (response && (response.body || []).length) { return resolve() }; return reject();` – Sergey Bondarenko Nov 05 '20 at 16:01
  • i tried that but even if the user does not exist it still goes to resolve and it does not go to the reject – shafeen sulaiman Nov 08 '20 at 05:32
  • 1
    I think you are using this construction incorrectly. You need to use something like that: `isUserExists().then(function(){console.log('user found')}, function(){console.log('user not found')})` – Sergey Bondarenko Nov 09 '20 at 09:09