1

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;

}
Pratish Shrestha
  • 1,712
  • 4
  • 17
  • 26

2 Answers2

2

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)
            });       
}
Eymen Elkum
  • 3,013
  • 1
  • 20
  • 34
0

Read more about promises

You should return promise, not value

fetchAll: function (resourceName) {

    new Promise(
        function(resolve, reject) {
            request
        .get(url + resourceName)
        .set('Accept', 'application/json')
        .end(function (err, res) {
            if(!err) {
                data = res.body;
                resolve(data);
            }else{
                console.log('error');
                reject('error');
            }
        });
        });


    return data;
}

Then in your code use this function like this:

fetchAll(someParam)
.then(function(result) {
    // do sth wirh result
});

It helps to works with asynchronous nature of AJAX requests.

suvroc
  • 3,058
  • 1
  • 15
  • 29