简体   繁体   English

如何通过JavaScript中的多链函数返回对象

[英]how to return an object through multi chained functions in JavaScript

Hello there code wizards, 您好,代码向导,

I am trying to get json data from the specified url down below and use it in a React component outside of the getWeather() function. 我正在尝试从下面的指定网址获取json数据,并在getWeather()函数外部的React组件中使用它。 What are the efficient ways to pass along an object from the innermost to outside? 从最内到外传递物体的有效方法是什么? my console reads undefined. 我的控制台读取未定义。 I believe there is an issue with variable scoping... Thanks for an idea to solve it. 我认为变量范围界定存在问题...感谢您提出解决方案。

Below is the code 下面是代码

function getWeather() {
    var url = 'http://api.openweathermap.org/data/2.5/weather?zip=3000,au';
    var apiKey= "005fa98ae858a29acf836ecdefac0411";
    var httpRequest;
    makeRequest();
    var response;


    function makeRequest() {
        httpRequest = new XMLHttpRequest();
        httpRequest.onreadystatechange = responseMethod;
        httpRequest.open('GET', url + '&appid=' + apiKey);
        httpRequest.send();
    }

    function responseMethod() {
        if(httpRequest.readyState === 4) {
            if(httpRequest.status === 200) {
                updateUISucess(httpRequest.responseText);

            } else {

            }
        }
    }

    function updateUISucess(responseText) {
        return response = JSON.parse(responseText);
        // I would like to get this JSON object out so that it logs on the console.
    }

    return response;
};



console.log(getWeather());

Chrome, now allow return on you function, u need synchronous request. Chrome,现在允许您返回功能,您需要同步请求。 try node webkit for do you request. 请尝试请求节点webkit。

You can use the callback method pattern to get the data and use it outside 您可以使用回调方法模式来获取数据并在外部使用它

 //Get weather function which accepts a callback function as a parameter function getWeather(callback) { var url = 'http://api.openweathermap.org/data/2.5/weather?zip=3000,au'; var apiKey = "005fa98ae858a29acf836ecdefac0411"; var httpRequest; makeRequest(); function makeRequest() { httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = responseMethod; httpRequest.open('GET', url + '&appid=' + apiKey); httpRequest.send(); } function responseMethod() { if (httpRequest.readyState === 4) { if (httpRequest.status === 200) { try { //Parse response var data = JSON.parse(httpRequest.responseText); //Invoke callback function with first arg null and second with result callback(null, data); } catch (e) { //JSON parse failed //Invoke callback with first arg as error object callback(e) } } else { //Invoke callback with first arg as error object callback({ success: false, status: httpRequest.status }); } } } }; 

 function Weather(props) { return <p>{JSON.stringify(props.result)}</p>; } //Callback which accepts err and result function handleResult(err, result) { if (err) { //Check for errors and return early if needed console.log("Error!", JSON.stringify(err)); return; } //Assign to react state here console.log(result); const element = <Weather result ={result}/ > ; ReactDOM.render( element ); } //Invoke getWeather with callback function as parameter getWeather(handleResult); 

Because of ajax (asynchronous) process js run continuously by line. 由于ajax(异步)进程,js逐行连续运行。
just make a callback function and pass it to calling function. 只需创建一个回调函数并将其传递给调用函数即可。

 function getWeather(cb) { var url = 'http://api.openweathermap.org/data/2.5/weather?zip=3000,au'; var apiKey= "005fa98ae858a29acf836ecdefac0411"; var httpRequest; makeRequest(); var response; function makeRequest() { httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = responseMethod; httpRequest.open('GET', url + '&appid=' + apiKey); httpRequest.send(); } function responseMethod() { if(httpRequest.readyState === 4) { if(httpRequest.status === 200) { updateUISucess(httpRequest.responseText); } else { } } } function updateUISucess(responseText) { // return response = JSON.parse(responseText); // I would like to get this JSON object out so that it logs on the console. cb(response); } return response; }; getWeather(cb); function cb(res){ alert(res); console.log(res); } 

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

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