简体   繁体   中英

How to return a nodejs callback as a number, from a JSON object property value?

I am trying to do maths on a number within a JSON object (the price of a stock ticker).

I want it to be a variable called 'btcusd_price', that I can then use to do arithmetic with.

How do I get a variable i can work with?

https://tonicdev.com/npm/bitfinex

var Bitfinex = require('bitfinex');

var bitfinex = new Bitfinex('your_key', 'your_secret');

var btcusd_price;

btcusd_price = bitfinex.ticker("btcusd", function(err, data) {
  if(err) {
    console.log('Error');
    return;
  }
  console.log(data.last_price);
  return data.last_price;
});

typeof btcusd_price;
console.log(btcusd_price); //i'm trying to work with the price, but it seems to be 'undefined'?

You have to set the values when they are available, the code is async and you were using the value before it is applied to btcusd_price . Note that the proper way to use the variable is when the callback executes its code.

Please, see the working code below:

Bitfinex = require('bitfinex');

var bitfinex = new Bitfinex('your_key', 'your_secret');

var btcusd_price;

bitfinex.ticker("btcusd", function(err, data) {
  if(err) {
    console.log('Error');
    return;
  }

  btcusd_price = data.last_price;
  console.log(typeof btcusd_price);
  console.log(btcusd_price);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM