4

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

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'd like to use that list from this function in other functions or simply assign it to a variable. I understand that since the function is asynchronous (well, the https.get one), returning the list won't mean much as the other code will not wait for this function to finish. Do I have to put all the remaining code inside the response.end call? I know I'm missing something very obvious here...

2 Answers 2

4

You can accept a callback as a parameter and call it with the relevant data inside the response.end handler:

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

Then you can call the getList function and pass in a callback:

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

Of course other options are to use some library implementing the Promises pattern to avoid callback hell.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah! That's it! Of course the callback passes the value. Thanks, that helped tremendously.
-1

make the list as global or accessible

var list = []

//declare a get method

function getUpdatedList(){
  return list;
}

if you call before ajax finish you will get null anfter you will get the actual data array, but in normal cases just uses callback functions like

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.