Search code examples
javascriptajaxsuperagent

return data coming through an ajax call from a javascript function


i have an object with function as below: since it is making an ajax call, it just returns the empty array. how do i return the data after the response.

var data = [];
var ApiUtil = {
    fetchAll: function (resourceName) {
        request
            .get(url + resourceName)
            .set('Accept', 'application/json')
            .end(function (err, res) {
                if(!err) {
                    data = res.body;
                }else{
                    console.log('error');
                }
            });

        return data;

}

Solution

  • The return executes before the request ends, this is why the data is empty.

    You can simply use a callback.

    var ApiUtil = {
        fetchAll: function (resourceName, callback) {
            var data = [];
            request
                .get(url + resourceName)
                .set('Accept', 'application/json')
                .end(function (err, res) {
                    if(!err) {
                        data = res.body;
                    }else{
                        console.log('error');
                    }
                    callback && callback(data)
                });       
    }