OliT
OliT

Reputation: 3

How can I make my If statement run after the functions call

Hi I'm new to the asynchronous programming, nodejs and javascript overall. I'm trying to run the following code. I need the if statement if (parseFloat(binanceData.price, 10) > parseFloat(coinbaseData.data.amount, 10)) to run after the binancePrice() and coinbasePrice() function calls or else I get the error that the value of coinbaseData.data.amount is undefined. I tried around with the promises and callbacks calls and also with the await methods, but so far unsuccessful. What would be your siggestion?

// request BTC price on binance
function binancePrice() {
  request(binanceAPI, (error, response, body) => {
     binanceData = JSON.parse(body);

     if (!binanceData) {
       response.statusCode(404).json({});
       return;
  }
    console.log(`The price of 1 BTC is ${binanceData.price} for the last ${binanceData.mins} minutes`);
  });
}

// request BTC price on coinbase
function coinbasePrice() {
  request(coinbaseAPI, (error, resp, body) => {
    coinbaseData = JSON.parse(body);

    if (!coinbaseData) {
      resp.statusCode(404).json({});
      return;
    }
    console.log(`The price of 1 BTC on coinbase is ${coinbaseData.data.amount} in ${coinbaseData.data.currency}`);
  });
}

// Router
testPay.route('/exchange-routing')
  .get((req, res) => {
    const cryptoAmount = parseFloat(req.query.amount, 10);
    let exchange = '';
    let price = 0;
    console.log(`User chose this amount of BTC ${cryptoAmount}`);

    if (cryptoAmount > 0) {
      binancePrice();
      coinbasePrice();

      // check lower BTC price
      if (parseFloat(binanceData.price, 10) > parseFloat(coinbaseData.data.amount, 10)) {
        exchange = 'Coinbase';
        price = parseFloat(coinbaseData.price, 10);
      } else {
        exchange = 'Binance';
        price = parseFloat(binanceData.price, 10);
      }
      // send response to client
      const answer = {
        btcAmount: cryptoAmount,
        usdAmount: cryptoAmount * price,
        exchange,
      };
      res.json(answer);
    } else {
      res.send('The amount of BTC needs to be higher than 0.');
    }
  });

Upvotes: 0

Views: 49

Answers (1)

Sadegh
Sadegh

Reputation: 107

You should use Promises and async/await

 // request BTC price on binance
function binancePrice() {
  return new Promise((resolve, reject) => {
    request(binanceAPI, (error, response, body) => {
      const binanceData = JSON.parse(body);

      if (!binanceData) {
        response.statusCode(404).json({});
        reject(new Error('404'));
        return;
      }

      console.log(`The price of 1 BTC is ${binanceData.price} for the last ${binanceData.mins} minutes`);
      resolve(binanceData);
    });
  });
}

// request BTC price on coinbase
function coinbasePrice() {
  return new Promise((resolve, reject) => {
    request(coinbaseAPI, (error, resp, body) => {
      const coinbaseData = JSON.parse(body);

      if (!coinbaseData) {
        resp.statusCode(404).json({});
        reject(new Error('404'));
        return;
      }

      console.log(`The price of 1 BTC on coinbase is ${coinbaseData.data.amount} in ${coinbaseData.data.currency}`);
      resolve(coinbaseData);
    });
  });
}

// Router
testPay.route('/exchange-routing')
  .get(async (req, res) => {
    try {
      const cryptoAmount = parseFloat(req.query.amount, 10);
      let exchange = '';
      let price = 0;
      console.log(`User chose this amount of BTC ${cryptoAmount}`);

      if (cryptoAmount > 0) {
        const binanceData = await binancePrice();
        const coinbaseData = await coinbasePrice();

        // check lower BTC price
        if (parseFloat(binanceData.price, 10) > parseFloat(coinbaseData.data.amount, 10)) {
          exchange = 'Coinbase';
          price = parseFloat(coinbaseData.price, 10);
        } else {
          exchange = 'Binance';
          price = parseFloat(binanceData.price, 10);
        }
        // send response to client
        const answer = {
          btcAmount: cryptoAmount,
          usdAmount: cryptoAmount * price,
          exchange,
        };
        res.json(answer);
      } else {
        res.send('The amount of BTC needs to be higher than 0.');
      }
    } catch(e) {
      console.error(e);
    }
  });

Upvotes: 1

Related Questions