I have this code:
const request = require('request');
let url = "https://api.warframe.market/v1/items";
let options = {json: true};
let item_urls;
//const response;
request(url, options, (error, res, body) => {
if (error) {
return console.log(error)
};
if (!error && res.statusCode == 200) {
console.log(body);
item_urls = body.payload.items;
};
});
It works fine and returns the JSON to the variable item_urls
.
I then tried to wrap my own function around it like so:
const request = require('request');
let url = "https://api.warframe.market/v1/items";
let options = {json: true};
let item_urls;
//const response;
function getitems(){
request(url, options, (error, res, body) => {
if (error) {
return console.log(error)
};
if (!error && res.statusCode == 200) {
console.log(body);
item_urls= body.payload.items;
};
});
};
getitems()
But it doesn't work, item_urls
ends up being undefined. The code is identical except for being wrapped inside my function. In case you are wondering why I want to it wrapped inside a function - I need to pass a parameter to it but I've removed this logic for simplicity and to demonstrate the issue.
Thanks,
EDIT: Additional details I forgot to mention sorry.
So I am running this code directly line by line in my IDE and sending the lines to the node REPL so that I can test code line by line. If we look at the first block of code:
I highlight it all and run it. Since request is async, I wait for it to complete first, I know it's completed because the callback function outputs the body to the console, so I wait until I see a load of data get printed to the console, this is how I verify the command completed successfully. Straight after the line of code which outputs the body to the console it then dumps the body into my variable. To confirm this has worked I then type item_urls
at the REPL terminal itself and can see the output.
With the second block of code, I open a new REPL so everything is clean. I then execute all the lines of code again and wait... What I am expecting is for the request async call to take a few seconds to complete like the first code block. However, nothing get's outputted to the console. I wait up to 30 secs (the previous block of code only took around 5 secs) then I type item_urls
at the REPL terminal again and it says undefined.
I am convinced it has something to do with the async and callback nature but I can't figure out what.