0

i have more than 3 functions and i want to execute the first function and when it finish i will execute the second one and so on . this is the code im trying to use but it execute all functions in the some time .

var categoriesReady = $.Deferred();
var linksReady = $.Deferred();
var dataReady = $.Deferred();

function getCategories(){
  $.getJSON(serviceURL + 'get_categories', function(data) {
  cats = data.categories;
  $.each(cats, function(index, cat) {
   $("#menuIcons").append('<li><a data-ajax="false" href="ca.html?id='+cat.id+'">'+cat.title+'</a></li>');
  });
 });
 categoriesReady.resolve();
}

function getLinks(){
  $.getJSON(serviceURL + 'get_links', function(data) {
  links = data.links;
  $.each(links, function(index, link) {
   $("#menuIcons").append('<li><a data-ajax="false" href="link.html?id='+link.id+'">'+link.title+'</a></li>');
  });
 });
 linksReady.resolve();
}

function getLinks(){
  $.getJSON(serviceURL + 'get_links', function(data) {
  cats = data.categories;
  $.each(cats, function(index, cat) {
   $("#menuIcons").append('<li><a data-ajax="false" href="ca.html?id='+cat.id+'">'+cat.title+'</a></li>');
  });
 });
 linksReady.resolve();
}

function getData(){
  $.getJSON(serviceURL + 'get_links', function(data) {
  posts = data.posts;
  $.each(cats, function(index, post) {
   $("#menuIcons").append('A : '+post.content);
  });
 });
 dataReady.resolve();
}
function init(){
  $("body").append("3 function are done!");
}
$.when(getCategories(),getLinks(),getData()).then(init);

whats the problem ?

Hamzar
  • 83
  • 1
  • 9
  • You resolve the deferreds right away. You don't really need them, just return the $.getJSON, as in `return $.getJSON(...` and it will work – adeneo Apr 17 '15 at 01:02
  • The problem is that you are trying to execute asynchronous code in a synchronous fashion. If you need to do that - just place the next function call in the callback of the previous function. (For example when `getCategories()` is done- it calls `getLinks()` etc.) – YemSalat Apr 17 '15 at 01:02
  • Use the done function : http://stackoverflow.com/q/23065907/3155563 – Han Apr 17 '15 at 01:03
  • @adeneo i didn't got what you try to explain for me , could you please be more clear? – Hamzar Apr 17 '15 at 01:05
  • @YemSalat can you give me the idea method to asynchronous things? – Hamzar Apr 17 '15 at 01:06
  • Look at Aruns answer below – adeneo Apr 17 '15 at 01:06
  • this can help: http://stackoverflow.com/questions/2765411/is-it-possible-to-set-asyncfalse-to-getjson-call – regisls Apr 17 '15 at 01:07
  • use when for more information see https://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-requests-are-done – hmfarimani Apr 28 '18 at 06:45

3 Answers3

2

I do it usually this way

  var getCategories = function(){
           return $.getJSON(serviceURL + 'get_categories', function(data) {
                cats = data.categories;
                $.each(cats, function(index, cat) {
                    $("#menuIcons").append('<li><a data-ajax="false" href="ca.html?id='+cat.id+'">'+cat.title+'</a></li>');
                });
            });
        }
   var getLinks = function(){
            return $.getJSON(serviceURL + 'get_links', function(data) {
                links = data.links;
                $.each(links, function(index, link) {
                    $("#menuIcons").append('<li><a data-ajax="false" href="link.html?id='+link.id+'">'+link.title+'</a></li>');
                });
            });
        };

   var getData = function(){
            return $.getJSON(serviceURL + 'get_links', function(data) {
                posts = data.posts;
                $.each(cats, function(index, post) {
                    $("#menuIcons").append('A : '+post.content);
                });
            });
        } ;

  function init(){
        $("body").append("3 function are done!");
     }

  // chain your promises here
 getCategories().done(getLinks().done(getData().done(init())));

You can also add .fail() to handle errors for each Ajax call

Raja Khoury
  • 3,015
  • 1
  • 20
  • 19
  • that seems verry ease and good , the question is how can i get the results returned by every function? – Hamzar Apr 17 '15 at 01:11
  • If you look at each function (ajax call) you can handle error and success callback just as you did in the example above with the foreach - see here for more info about jQuery AJAX and returned handlers http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html – Raja Khoury Apr 17 '15 at 01:15
0

You only want to resolve when the operation finishes, so it needs to be placed inside the callback:

function getCategories(){
  $.getJSON(serviceURL + 'get_categories', function(data) {
        cats = data.categories;
        $.each(cats, function(index, cat) {
            $("#menuIcons").append('<li><a data-ajax="false" href="ca.html?id='+cat.id+'">'+cat.title+'</a></li>');
        });
        categoriesReady.resolve();
    });
}

..and do the same for all others

Austin Greco
  • 32,997
  • 6
  • 55
  • 59
  • what about if i use $.ajax ? or a function that doesn't support callback? – Hamzar Apr 17 '15 at 01:07
  • Any asynchronous operation will have some type of callback (it may be named something else) but the idea is just that you want to resolve only after it's finished. `$.ajax` has several different callbacks based on response – Austin Greco Apr 17 '15 at 01:13
0

There are no need to use custom deferred as ajax returns a promise

function getCategories() {
    return $.getJSON(serviceURL + 'get_categories', function (data) {
        cats = data.categories;
        $.each(cats, function (index, cat) {
            $("#menuIcons").append('<li><a data-ajax="false" href="ca.html?id=' + cat.id + '">' + cat.title + '</a></li>');
        });
    });
}

function getLinks() {
    return $.getJSON(serviceURL + 'get_links', function (data) {
        links = data.links;
        $.each(links, function (index, link) {
            $("#menuIcons").append('<li><a data-ajax="false" href="link.html?id=' + link.id + '">' + link.title + '</a></li>');
        });
    });
    linksReady.resolve();
}

function getData() {
    return $.getJSON(serviceURL + 'get_links', function (data) {
        posts = data.posts;
        $.each(cats, function (index, post) {
            $("#menuIcons").append('A : ' + post.content);
        });
    });
}

function init() {
    $("body").append("3 function are done!");
}
getCategories().then(function () {
    var deferred = $.Deferred();
    $.when(getLinks(), getData()).done(function () {
        deferred.resolve();
    });
    return deferred.promise();
}).then(init);

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531