My goal is to create a function that does the request and then returns the token
You cannot make a function that returns a value that it doesn't have immediately. You can only return a promise.
Then in some other part of code you can either wait for the promise to be fulfilled by using the then handler, or you can use something like:
var token = await getToken();
inside of an async function to wait for that value to be available, but only if the getToken()
function returns a promise.
For example, using the request-promise
module it would be something like:
var rp = require('request-promise');
function getToken() {
// this returns a promise:
return rp('http://www.example.com/some/path');
})
And then some other function:
function otherFunction() {
getToken().then(token => {
// you have your token here
}).catch(err => {
// you have some error
});
}
Or, with async function
something like this:
async function someFunction() {
try {
var token = await getToken();
// you have your token here
} catch (err) {
// you have some error
}
}
See: https://www.npmjs.com/package/request-promise
Note that async function
and await
is define in ECMAScript 2017 Draft (ECMA-262) which is not final yet at the time of this writing as of March 2017 (it will be in June 2017).
But it's already available in Node since v7.6 (and it was available since v7.0 if you used the --harmony
flag). For the compatibility with Node versions, see:
If you want similar features for older Node versions with slightly different syntax, you can use modules like co or Promise.coroutine from Bluebird.