0

I have a jQuery function/plugin that returns a value but there is a function that is called before returning that needs to be finished before returning or else the value returned is incorrect.

If I put the return line inside function1().done, it doesn't seem to return anything at all. If I put it outside, it returns before function1 is finished.

Below is not the real code but I am using this example to convey my problem. Hope it makes sense.

$(function(){
    function1().done(function(){
        console.log('function1 is done!');
        return "this value needs to be returned only after function1 above is finished";
    });



});

function function1(){
    var dfrd1 = $.Deferred();
    var dfrd2= $.Deferred();

    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function1 is done!');
        dfrd1.resolve();
    }, 1000);

    setTimeout(function(){
        // doing more async stuff
        console.log('task 2 in function1 is done!');
        dfrd2.resolve();
    }, 750);

    return $.when(dfrd1, dfrd2).done(function(){
        console.log('both tasks in function1 are done');
        // Both asyncs tasks are done
    }).promise();
}
renny
  • 213
  • 3
  • 10
  • You can't, that's what asynchronous means, you have to wait for the function to finish before you can use the returned data. – adeneo Oct 21 '16 at 23:24
  • I do want to return the data only after the function is finished. I tried moving the return inside function1().done(function() but it doesn't seem to return anything at all. If I put it outside, return runs before function1 is finished. – renny Oct 21 '16 at 23:28
  • Think of this way, you can't return a package today, that you're going to receive next week. You simply can not return the response because it's not there, yet. – adeneo Oct 21 '16 at 23:30
  • I know and that is exactly what I am trying to avoid. I only want to return when function1 is finished doing its thing. Currently, my return value is wrong because it returns a value before all the calculations that are needed are finished running. I am trying to figure out how to solve this problem. and figure out how to call the return. – renny Oct 21 '16 at 23:32
  • I'll try to be clearer, you **can not** return, that train has left the station, **you have to** work with the data you receive or whatever your async function does, **inside the `done()` callback**. – adeneo Oct 21 '16 at 23:34

0 Answers0