How can the variables obtained by json in node.js be converted into global variables?

something like this:

var aaa = 0;
http.get (" http://abc.com/api"", function (res) {

var json = "";
res.on("data", function (d) {
    json += d;
});
res.on("end",function(){
    //
    json = JSON.parse(json);
    aaa = json;
});

}). On ("error", function (e) {

console.error(e);

});
console.log (aaa);

because of the problem of returning data asynchronously, aaa actually does not get the data of json, and the output is still zero; how to make the output of aaa to the value of json?

Mar.01,2021

your question should be changed to how can the data returned asynchronously be obtained by Synchronize.

just like Promise, all data operations should operate in the chain. Similarly, your asynchronous callback should also operate on in the callback function.

you can take a look at the flow of Node.js to implement the asynchronous Imax O operation:

  1. pass parameters and callback into Node core module
  2. Node core module encapsulates the passed parameters and callback functions into a request object
  3. push the request object into the Icano thread pool to wait for the result
  4. (note that this is why your Synchronize can't get the data) the upper JavaScript code continues to execute!
  5. after the operation is completed, store the result in the result of the request object and notify the upper code
  6. check whether there is a completed I li O operation in each time loop, and then add the request object to the observer queue, and then when the event is handled < / user >
  7. when handling the IWeiO observer event, take out the callback object encapsulated in the request object, execute the callback, take result as a parameter, and complete the callback

it is suggested that if you don't like the way callback functions are written, you can use ES7's Async/Await syntax.

give me an example?:

async function fn() {
    let aaa = 0;
    let json = '';
    try {
        const res = await http.get('http://abc.com/api"');
        ...
        aaa = res.result;
        console.log(aaa);        
    } catch(err) {
        console.log(`error: ${err}`);
    }
}

is this much more comfortable ~ but it is recommended to choose the latest LTS version of Node.js

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-7b71a2-29bca.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-7b71a2-29bca.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?