Using Javascript When and Done Function

I am trying to call two different functions in a third function, but one by one. One function has an ajax call whose values ​​are used in another function. it is step by step. I do not want to use it in another.

function f1()
{
    // ajax call 
    return r1
}

function f2(r2)
{
    // do some of the work based on r2
}

function f3()
{
    $.when(f1()).done(function(data){
            f2(data)

    });
}

I also tried with $ .when (). then (); but still useless.

Thanks in advance.

UPDATE: - Below is the answer for my Question based on the solution provided by @dreamweiver.

var json_data = '';
function f1()
{

    $.ajax({
         url: "test.php",
         method: "POST",
         async : false,
         data: { },
         success:function(data){
            json_data = eval(data);
         }

       });  


}

function f2(t)
{

    console.log("values is "+t);
}

function f3()
{
    $.when(f1()).done(function(){
        f2(json_data);
   });
}

Thank you all for your feedback.

+4
source share
2 answers

Try this way, I tested locally and works great

function deferredCalls () {
   var jsonData = '';
   var f1 = function ()
   {
       // ajax call 
       $.ajax({
         url: "test.html",
         method: "POST",
         data: { id : menuId }
       }).done(function(data) {
          jsonData = data; //set the data
       });
   }

   var f2 = function (data)
   {
     // do some of the work based on data
     if(!!data){
       //process the data
     }
   }
   $.when(f1).done(function(){
        f2(jsonData);
   });
 }

f1 , ajax , jsonData. , f2, jsonData, , , f1.

:)

0

:

function f1() {
    // Or some other Ajax request that returns a promise
    return $.getJSON('path/to/your/service');
}

function f2(r2) {
    // ...
}

f1().done(f2);
0

All Articles