简体   繁体   English

如何从JSON对象属性值以数字形式返回Node.js回调?

[英]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). 我正在尝试对JSON对象(股票报价器的价格)中的数字进行数学运算。

I want it to be a variable called 'btcusd_price', that I can then use to do arithmetic with. 我希望它是一个名为“ btcusd_price”的变量,然后可以用来进行算术运算。

How do I get a variable i can work with? 如何获得可以使用的变量?

https://tonicdev.com/npm/bitfinex 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 . 您必须设置可用的值,代码是异步的,并且在将其应用于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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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