繁体   English   中英

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

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

我正在尝试对JSON对象(股票报价器的价格)中的数字进行数学运算。

我希望它是一个名为“ btcusd_price”的变量,然后可以用来进行算术运算。

如何获得可以使用的变量?

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'?

您必须设置可用的值,代码是异步的,并且在将其应用于btcusd_price之前正在使用该值。 请注意,使用变量的正确方法是在回调执行其代码时。

请查看下面的工作代码:

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