Search code examples
javascriptnode.jspromisebluebird

Then is not a function promise error


I'm new to promises and I use the bluebird docs to get data from async code

what I tried is the following:

the error is:

getToken.then is not a function

How can I avoid it?

This file connection.js

return connection.getToken.then(function(connToken){

   console.log(connToken);

}).catch({


})

This the code of getToken in moduleB

const request = require("request-promise");
const Promise = require("bluebird");
module.exports = {


    getToken: function () {


        return new Promise((resolve, reject) => {
            let options = {
                method: 'POST',
                url: 'https://authentication.arc.com/oauth/token',
                headers: {
                    grant_type: 'client_credentials',
                    authorization: 'Q0MDdmMCFiMTc0fGNvlQVRDWThDNDFsdkhibGNTbz0=',
                    accept: 'application/json;charset=utf-8',
                    'content-type': 'application/x-www-form-urlencoded'
                },
                form: {
                    grant_type: 'client_credentials',
                    token_format: 'opaque&response_type=token'
                }
            };


            request(options)
                .then(function (body) {

                    return body;
                })
                .catch(function (err) {
                    return err;          
                });
        })

    }
}

Solution

  • You need to actually call the function.

    connection.js

    return connection.getToken() // note the parentheses ()
      .then(function(connToken){
        console.log(connToken);
      })
      .catch(function(error){
        console.error(error);
      });