I am trying to create a function that returns the data from a Node http request, so that the data can be stored in a variable to be used afterwards. The function places the data in an array, and the array is returned from the function. Then, I invoke the function and assign the result to a variable.
I am able to successfully get the data with the http request and place the date in the array, but there are two problems with the current implementation.
When I try to access the variable containing the function results, the result is
Promise { <pending> }
. I understand this is because the async function hasn't completed doing its work, but I'm not sure how set up the code so that it waits to use the variable until after the promise is done. The function is an async function, and it is awaiting the http request, so I thought it would wait for the function to complete its work before moving down to the next line of code (such as the console of the variable).When I use setTimeout to look at the variable after some time has passed, the variable does contain what the function returned, so it does receive the data eventually, but the data in the variable is still inside a promise, so I am unable to retrieve the items from it.
This is my code:
require('dotenv').config();
const https = require('https');
const potionsUrl = process.env.POTIONS_URL;
const getData = async (url) => {
const list = [];
await https
.get(url, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
const parsedData = JSON.parse(data);
list.push(...parsedData);
});
})
.on('error', (error) => {
console.log(error);
});
return list;
};
const potions = getData(potionsUrl);
console.log(potions);
// Do other stuff with potions
This is what displays in the console:
IMMEDIATE POTIONS
Promise { <pending> }
POTIONS AFTER 5 seconds:
Promise {
[
{
id: 11,
potion: 'Truthy Yes Serum',
spell_level: 2,
tasty: false,
brand: 'Arkex Brews'
},
{
id: 14,
potion: 'Langstons Majical Beans',
spell_level: 13,
tasty: false,
brand: 'Arkex Brews'
}
]
}