我在将变量http.get输出未定义后尝试记录该变量时,无法将值分配给btcprice。我知道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;
});
})
最佳答案
我根据您的解释创建了一个示例。您可以看到,只有在完全收到响应之前,才重新分配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