0

I have a function

function GetITStaffList(){
    var go_path = "Server/ITComplains.php?action=GetITStaffList&vars=0";
    $jqLibrary.get(go_path,
        {}, function(data)
        {
            var parseData = JSON.parse(data);
            console.log("GetPendingAndInProgressComplainsByGeneratorId : ", parseData);

            return parseData;
        });
}

I am calling this somewhere in the code like this

var ITStaffList = GetITStaffList();
MakeDropDownITStaff(ITStaffList);

But the problem is each time it is returning null. I know that I have to use callback and something like a promise but I don't how to fit this thing in my context. How do I write a reusable function with ajax call that returns data on demand.?

Charlie
  • 22,886
  • 11
  • 59
  • 90
Muhammad Faizan Khan
  • 10,013
  • 18
  • 97
  • 186
  • you can't return data synchronously from an asynchronous call (like AJAX is, i.e. the first A in AJAX stands for Asynchronous) - see https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Jaromanda X Jan 03 '18 at 06:41
  • 1
    Possible duplicate of [How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?](https://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-re) – Core972 Jan 03 '18 at 06:53

1 Answers1

1

Return a promise instead.

function GetITStaffList(){

    return new Promise(function(resolve){

       var go_path = "Server/ITComplains.php?action=GetITStaffList&vars=0";
       $jqLibrary.get(go_path,
           {}, function(data)
           {
               var parseData = JSON.parse(data);
               console.log("GetPendingAndInProgressComplainsByGeneratorId : ", parseData);

            resolve(parseData);    //Notice this
        });
    })
}

Now you can call the function and wait for data.

GetITStaffList().then(function(data){
    console.log(data)
})
Charlie
  • 22,886
  • 11
  • 59
  • 90
  • Thanks it worked but it is very comlicated. what will i do if i have to get data from multiple request. Do i need to write nested then? Like in then function another then? – Muhammad Faizan Khan Jan 03 '18 at 07:04
  • ES6 supports "async" functions - which take the complications of promises away. Please google for that. Also, you can use some libraries which implement promise flow control. https://www.npmjs.com/package/promise-waterfall – Charlie Jan 03 '18 at 07:33