This makes perfect sense! I tried using a callback and it worked, but I didn't like the mess I created so I made the code in my original question. Your solution is clean and makes sense. Also I will use getInventoryContents. Thanks a bunch!
Oh but one question. getInventoryContents has a steamid param, so I'd assume you can fetch other users inventories, but there is a getUserInventoryContents function for that. What's the difference?
I also made this mistake as a beginner.
You have a misunderstanding of asynchronous code in javascript. Fetching the inventory takes some time, and so by returning inventory, the variable is being returned before the program can even fetch your inventory.
You will have to create your own callback and that works by taking in a function as a callback parameter, and then executing that function once the inventory has been fetched.
const getInventory = (callback) => {
manager.loadInventory(730, 2, true, (err, inventory) => {
if (err) {
callback(err);
}
else {
callback(null, inventory);
}
})
}
I personally prefer to check for errors first, but whatever you prefer you can change it to.
When we want to fetch the inventory we use it like so:
getInventory((err, inventory) => {
if (err) {
console.log('error getting the inventory :(');
}
else {
// code to do whatever you want with inventory here
}
})
I also saw that you are using the loadInventory method, it would be much better if you used the getInventoryContents method as it says this in the docs:
EDIT: Callbacks are getting ugly nowadays imo so you can also use a promise if you prefer:
const getInventory = () => {
return new Promise((resolve, reject) => {
manager.loadInventory(730, 2, true, (err, inventory) => {
if (err) {
reject(err);
} else {
resolve(inventory);
}
});
});
}
getInventory()
.then(inventory => {
// do whatever here
})
.catch(err => console.log('oops'));
// OR
// this must be inside a async function
try {
const inventory = await getInventory();
// do whatever here
} catch (err) {
console.error(err)
}