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)
})
Sign up to request clarification or add additional context in comments.

2 Comments

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

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.