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.?

2

1 Answer 1

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)
})
2
  • 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? Commented Jan 3, 2018 at 7: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. npmjs.com/package/promise-waterfall
    – Charlie
    Commented Jan 3, 2018 at 7:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.