在NodeJS中使用http.get存储变量值?

时间:2017-12-16 02:26:14

标签: javascript node.js

我无法将值分配给btcprice,当我尝试在http.get之后记录变量时,它输出undefined。我知道http.get是异步发生的,但不知道该怎么做才能解决这个问题。任何帮助都会很棒!谢谢。

const http = require('http');
var btcprice;
// request api
http.get(
{
host: 'api.coindesk.com',
path: '/v1/bpi/currentprice.json'
},
function(response){
  // get data
  let body = '';
  response.on('data', function(d) { body += d; });
  response.on('end', function() {
  // manipulate received data
  let parsed = JSON.parse(body);
  btcprice = parsed.bpi.USD.rate;
  });
})

1 个答案:

答案 0 :(得分:1)

我根据你的解释创建了一个例子。您可以看到,只有在btcprice具有默认值btcprice之前完全收到回复时才会重新分配undefined

const http = require('http');
let btcprice;

// request api
http.get({
  host: 'api.coindesk.com',
  path: '/v1/bpi/currentprice.json'
}, (response) => {
  // get data
  let body = '';
  response.on('data', function(d) {
    body += d;
  });
  response.on('end', function() {
    // manipulate received data
    let parsed = JSON.parse(body);
    btcprice = parsed.bpi.USD.rate;
    console.log(btcprice); // btcprice will now have an value
  });
})

console.log(btcprice); // btcprice will be "undefined" since the response isn't already available