How to use data returned by an asynchronous function in Node.js?

I want to define a function that gets me a list of specific identifiers from a GET request response:

var getList = function (){

    var list = [];

    https.get(options).on('response', function (response) {
        var body = '';
        response.on('data', function (chunk) {
            body += chunk;
        });
        response.on('end', function () {
            var obj = JSON.parse(body);
            for (i=0 ; i<obj.length ; i++){
                list.push(obj[i].id);
            }
            //console.log(list);
            //return list;
        });
    });
};

Now I would like to use this list from this function in other functions or just assign it to a variable. I understand that since the function is asynchronous (well, https.getone), returning a list will not mean much, since other code will not wait for the completion of this function. Should I put all the remaining code inside the call response.end? I know that I am missing something very obvious here ...

+4
source share
2 answers

response.end:

var getList = function (successCallback){

    var list = [];

    https.get(options).on('response', function (response) {
        var body = '';
        response.on('data', function (chunk) {
            body += chunk;
        });
        response.on('end', function () {
            var obj = JSON.parse(body);
            for (i=0 ; i<obj.length ; i++){
                list.push(obj[i].id);
            }

            // invoke the callback and pass the data
            successCallback(list);
        });
    });
};

getList :

getList(function(data) {
    // do some stuff with 'data'
});

, - , Promises, callback.

+4

var list = []

//declare a get method

function getUpdatedList(){
  return list;
}

ajax, , , ,

function getList(callback){

    ///
    //
    response.on('end', function () {
        var obj = JSON.parse(body);
        for (i=0 ; i<obj.length ; i++){
            list.push(obj[i].id);
        }
        callback(list);
    });
}
-1

All Articles