Friday, 7 April 2017

Get return value from async function from a variable call

For the past few days I have been searching for an answer and I am now wondering if it isn't possible at all.

What I'm trying to accomplish is getting the return value from an asynchronous function for a variable.

For example, you can do things like this for a non-async function:

function getRandomNumber() {
    return Math.floor(Math.random() * 100)    
}

var randomNumber = getRandomNumber(); // This gets a random number between 1 and 100

I want to get roughly the same method of dong that, by calling an function and using the variable for further use, but I can't seem to get the value back if I'm using a async function.

I am using Node.js and node-fetch to try and get information from an JSON API. My code is:

async function foo(){
    var data = await fetch("url/to/api/resource");
    return data.json();
}

console.log(foo()); // Returns 'Promise { <pending> }'

// More realisticly on what I am trying to do is use it in another file. It still returns 'Promise { <pending> }' however.
module.exports.fetchInfo = foo()

Using things like callbacks and .then() will work, but they aren't returned back to the variable.

Does anyone have any idea on how I could accomplish this? If not, is there a better way (or one that actually works) which I could get data defined using a variable?



via Sam Bunting