简体   繁体   English

JS 从 http.get 分配 var

[英]JS assign var from http.get

trying to assign json data to global js variables... why does this not work... tried using fetch and this http.get keep getting undefined for the global vars when console.log displays them any help?试图将 json 数据分配给全局 js 变量...为什么这不起作用...尝试使用 fetch 和此 http.get 当 console.log 显示它们有任何帮助时,全局变量一直未定义?


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)

You have to wait until all data has been received and processed.您必须等到所有数据都已收到并处理完毕。

You can use for example "await / async"...您可以使用例如“等待/异步”...

For demonstration purposes, I set a simple timeout at the end.出于演示目的,我在最后设置了一个简单的超时。

    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);

https.get is an asynchronous function, to make it some code execute after it is completed you have to resort to the old good callback. https.get是一个异步的 function,要让它在完成后执行一些代码,你必须求助于旧的好回调。 Now, since you have it executed inside another function, to execute some code after that function is done with the request, you would have to wrap the http.get call in an Promise and await for it to finish , then execute whatever code you want after the getNews() call in an IIFE. Now, since you have it executed inside another function, to execute some code after that function is done with the request, you would have to wrap the http.get call in an Promise and await for it to finish , then execute whatever code you want在 IIFE 中的getNews()调用之后。

Take a look:看一看:

var testUrl = "https://tools.learningcontainer.com/sample-json.json"
var firstName = ""
var lastName = ""
var age = 0
function getNews(url1) {
    return new Promise(
        (resolve, reject) => {
            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);
                    }
                    resolve();
                });

                response.on('error', function () {
                    reject(error);
                })
            })
        }
    )
}

function assignData(data) { // function to process data
    firstName = data.firstName
    lastName = data.lastName
    age = data.age
    // console.log(firstName,lastName,age)
}

(async function(){
    await getNews(testUrl);
    console.log(firstName, lastName, age)
})();

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

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