0

I am writing a steam bot and am trying to check, if one of the items in a trade is worth below 1 USD. I need to access the "pass" variable, but it never works. Can someone help?

    var receive = offer.itemsToReceive;
    var pass = true;
    receive.forEach(function(id) {
      var args = id.split(",");
      market.getItemPrice("some app id", some item name).then(function(result) {
        var json = JSON.parse(JSON.stringify(result)); // returns e.G $0.08
        var price = parseFloat(json.median_price.substring(1));

        if(price*100 < 100) {
           pass = false;
        }
      });
    });
biss
  • 57
  • 7
  • If you want access to the pass variable after it has been changed, you will have to write a function that returns pass as a promise. assuming getItemPrice returns a promise. var pass = true; getItemPrice("some app id").then(function(result) { return new Promise((resolve, reject) => { pass = false; return resolve(pass) }); }).then(pass => console.log(pass)); //call a different function with pass – John Franke Aug 22 '18 at 20:02

1 Answers1

1

This question is asked a lot, but hopefully explaining it in your own problem's terms will help you understand.

Your code should wait for any possibility of pass = false;, but it doesn't because you call a asynchronous function --- imagine the code immediately moves on after calling that. Your foreach function is immediately processed and the next line is called until .getItemPrice responds some time later.

So instead, to "wait" for all the results, you can do something like:

var receive = offer.itemsToReceive;
var pass = true;
var itemReceivePromises = receive.map(id=>{
  var args = id.split(",");
  return market.getItemPrice("some app id", some item name).then(function(result) {
    var json = JSON.parse(JSON.stringify(result)); // returns e.G $0.08
    var price = parseFloat(json.median_price.substring(1));

    if(price*100 < 100) {
       pass = false;
    }
  });
});
Promise.all(itemRecievePromises).then(results=>{
  console.log('pass',pass);
});

However, you should pass the "pass" result back through the promise instead of using a higher scoped variable.

Cody G
  • 8,368
  • 2
  • 35
  • 50