javascript – How do I make it asynchronous?

Question:

NodeJS app. There is such a piece of code:

var isAccepted;
offers.getOffer({tradeOfferId: offer.tradeofferid}, function (err, o) { 
   if (err || (o == null) || (typeof o.response.offer.trade_offer_state == "undefined")) {
      helper.msg('Cant load offer state. It can be accepted, but we cant check it. Returning');
      isAccepted = false;
      return;
   }
   if (o.response.offer.trade_offer_state == "3") {
   isAccepted = true;
   }
   else {
   isAccepted = false;
   }
   return;
});

if (!isAccepted) {
   io.emit('tradeoffer-msg', { steamid: offer.steamid_other, type: 6 });
   return;
}

The problem is that if (!isAccepted) is executed before we get the result from the server in offers.getOffer . I could of course put

 if (!isAccepted) {
   io.emit('tradeoffer-msg', { steamid: offer.steamid_other, type: 6 });
   return;
}

in offers.getOffer , but then return will work for an unnamed function in offers.getOffer , and not "outside" as I need. Question: how to make the application wait for a response in this case?

Answer:

You will not do an asychronic return, it does not work that way. Please provide more code, as the problem is not in this piece. Instead of return, you need to use a callback function in some form.

var isAccepted;
offers.getOffer({tradeOfferId: offer.tradeofferid}, function (err, o) { 
   if (err || (o == null) || (typeof o.response.offer.trade_offer_state == "undefined")) {
      helper.msg('Cant load offer state. It can be accepted, but we cant check it. Returning');
      isAccepted = false;
      return;
   }
   if (o.response.offer.trade_offer_state == "3") {
   isAccepted = true;
   }
   else {
   isAccepted = false;
   }
   if (!isAccepted) {
      io.emit('tradeoffer-msg', { steamid: offer.steamid_other, type: 6 });
      callback()
   }
});

PS You can, of course, make this code run as if synchronously, but such things write crayfish for crabs.

Scroll to Top