vrtgn Posted May 28, 2019 Report Posted May 28, 2019 Hello. I have the function below which gets an item id by calling the inventory, then seeing which item's name is correct and then returns the id, however when i return the ID, it does not show correctly: it shows undefined. I have tried both .assetid and .id But when i put in the function console.log(inventory.assetid) it logs the id, but when i call the function it doesnt return the id! Please halp thank you function getID(itemname) { manager.getInventoryContents(440, 2 , true, function(err, inventory) { if (err) { console.log(err) return; } else { //console.log(inventory); for (var i = 0; i < inventory.length; i++) { if (inventory.market_hash_name === itemname) { return inventory.id; } } } }) Quote
Dr. McKay Posted May 28, 2019 Report Posted May 28, 2019 You have a misunderstanding of how asynchronous code works in JavaScript. You need to pass a callback to getID and call it with the item ID you're looking for. Quote
vrtgn Posted May 29, 2019 Author Report Posted May 29, 2019 (edited) You have a misunderstanding of how asynchronous code works in JavaScript. You need to pass a callback to getID and call it with the item ID you're looking for. thanks for your quick reply so like this? function getID(itemname, callback) { manager.getInventoryContents(440, 2 , true, function(err, inventory) { if (err) { console.log(err) return; } else { //console.log(inventory); for (var i = 0; i < inventory.length; i++) { if (inventory.market_hash_name === itemname) { callback(inventory.id); return; } } } }) when calling :getID("The Diamondback", function logID(id) {//do something with id}) Edited May 30, 2019 by vrtgn Quote
Dr. McKay Posted May 30, 2019 Report Posted May 30, 2019 Yep, that looks right. Although be aware that your callback function there is going to be called once for every item in your inventory that has a matching name. Put a return statement after the callback invocation to avoid that. Quote
vrtgn Posted May 30, 2019 Author Report Posted May 30, 2019 Yep, that looks right. Although be aware that your callback function there is going to be called once for every item in your inventory that has a matching name. Put a return statement after the callback invocation to avoid that. It works now! Thanks so much for your help. Solution: thanks for your quick reply so like this? function getID(itemname, callback) { manager.getInventoryContents(440, 2 , true, function(err, inventory) { if (err) { console.log(err) return; } else { //console.log(inventory); for (var i = 0; i < inventory.length; i++) { if (inventory.market_hash_name === itemname) { callback(inventory.id); return; } } } }) when calling :getID("The Diamondback", function logID(id) {//do something with id}) Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.