javascript - JS 从 http.get 分配 var
问题描述
试图将 json 数据分配给全局 js 变量...为什么这不起作用...尝试使用 fetch 并且当 console.log 向全局变量显示任何帮助时,此 http.get 一直未定义全局变量?
var https=require('https');
var testUrl="https://tools.learningcontainer.com/sample-json.json"
var firstName=""
var lastName=""
var age=0
function getNews(url1) {
var request = https.get(url1, function(response) {
// console.log(response.statusCode); // for testing to see the status code
var body = ''; // start with an empty body since node gets responses in chunks
// Read the data
response.on('data', function(chunk) {
body += chunk;
});
response.on('end', function() {
if ( response.statusCode === 200 ) {
data=JSON.parse(body)
//console.log(data)
}
assignData(data)
})
})
}
function assignData(data) { // function to process data
firstName=data.firstName
lastName=data.lastName
age=data.age
console.log(firstName,lastName,age)
}
getNews(testUrl);
console.log(firstName,lastName,age)
解决方案
您必须等到所有数据都已收到并处理完毕。
您可以使用例如“等待/异步”...
出于演示目的,我在最后设置了一个简单的超时。
var https = require('https');
var testUrl = "https://tools.learningcontainer.com/sample-json.json"
var firstName = ""
var lastName = ""
var age = 0
function getNews(url1) {
var request = https.get(url1, function (response) {
// console.log(response.statusCode); // for testing to see the status code
var body = ''; // start with an empty body since node gets responses in chunks
// Read the data
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function () {
if (response.statusCode === 200) {
data = JSON.parse(body)
//console.log('[response]',data)
}
assignData(data)
})
})
}
function assignData(data) { // function to process data
firstName = data.firstName
lastName = data.lastName
age = data.age
console.log('[assignData]', firstName, lastName, age)
}
getNews(testUrl);
console.log('[resultToEarly]', firstName, lastName, age)
setTimeout(function() {
console.log('[resultAfterWaiting]', firstName, lastName, age)
}, 3000);
推荐阅读
- java - 重建后Android Studio(R.java文件)上的编码错误
- angular - Angular:如何从 ng-bootstrap 导入和使用 Carousel?
- java - 将三元运算符作为方法参数传递是否会影响性能
- python - Matplotlib 将轴显示为二进制
- php - 循环遍历数组php中的数组
- javascript - JavaScript 测试 (mocha) 代码组织
- web-services - 从哪里开始学习 SOAP Web 服务(在 java 中)?
- vue.js - vue-test-utils shallowMount:每次测试的执行时间都会增长
- c# - 如何在 Unity 中显示来自 higcharts.com 的图表?- 使用 C#
- android - 从外部文件目录获取图片