Async run for javascript by using listeners

Posted by CharlieShi on Stack Overflow See other posts from Stack Overflow or by CharlieShi
Published on 2014-05-30T03:15:06Z Indexed on 2014/05/30 3:25 UTC
Read the original article Hit count: 77

Filed under:
|
|

I have two functions, the names are Function3, Function4, Function3 will send request to server side to get jsondata by using ajax, which, however, will take about 3 seconds to complete. Function4 is a common function which will wait for Function3's result and then action. My code puts below:

  function ajaxRequest(container)
  {
    $.ajax({
        url: "Home/GetResult",
        type: "post",
        success: function (data) {
            container.append(data.message);
        }
    });
  }

  var eventable = {
    on: function (event, cb) {
        $(this).on(event, cb);
    },
    trigger: function (event) {
        $(this).trigger(event);
    }
}

var Function3 = {
    run: function () {
        var self = this;
        setTimeout(function () {
            ajaxRequest($(".container1"));
            self.trigger('done');
        }, 500);
    }
}

var Function4 = {
    run: function () {
        var self = this;
        setTimeout(function () {
            $(".container1").append("Function4 complete");
            self.trigger('done');
        },500);
    }
}

$.extend(Function3, eventable);
$.extend(Function4, eventable);

Function3.on('done', function (event) {
    Function4.run();
});

Function4.on('done', function () {
    $(".container1").append("All done");
});

Function3.run();

but now the problem is, when I start the code , it always show me the result as : first will appear "Function4 complete", then "All done" follows, 3 seconds later, "Function3 complete" will appear. That's out of my expection because my expection is "Function3 complete" comes first, "Function4 complete" comes second and "All done" is expected as the last one.

Anyone can help me on this? thx in advice.

EDIT: I have included all the functions above now. Also, you can check the js script in JSFIDDER: http://jsfiddle.net/sporto/FYBjc/light/ I have replaced the function in JSFIDDER from a common array push action to ajax request.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about asynchronous