i want to return value after the for loop but for some reason reads the value brefore the loop
client.on('friendMessage', (steamID, message) => {
var cmd;
if(cmd = message.match(/^!amount (\D+)/)) {
var item_idz = cmd[1];
console.log(amnt(item_idz))
}
});
function amnt(item_idz,steamID) {
manager.getUserInventoryContents("[U:1:1227885041]", 440, 2, true, (err, inventory) => {
if(err) {
console.log("coś sie zepsuć");
} else {
var ew = 0;
for(var p = 0; p< inventory.length; p++) {
if(inventory[p].name == item_idz) {
ew++;
console.log(ew)
}
}
if(steamID != null) {
client.chatMessage(steamID, ew.toString());
} else {
return ew;
}
}
});
}
output: 7656119884397**** said !amount Crimson Cache Case undefined 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
This console.log show undefined Because you use callback and amnt append in javascript event stack until the process has been finish
On other hand function amnt return nothing cause you execute callback function and return nothing
You try this code for print data:
if(cmd = message.match(/^!amount (\D+)/)) {
var item_idz = cmd[1];
amnt(item_idz, (error, data) => console.log(data));
}
function amnt(item_idz, steamID, next) {
manager.getUserInventoryContents('[U:1:1227885041]', 440, 2, true, (err, inventory) => {
if (err) {
console.log('coś sie zepsuć');
} else {
var ew = 0;
for (var p = 0; p < inventory.length; p++) {
if (inventory[p].name == item_idz) {
ew++;
console.log(ew);
}
}
if (steamID != null) {
client.chatMessage(steamID, ew.toString());
next(null);
} else {
next(null, ew);
}
}
});
}