0

I can write a callback function that will halt execution of one script until another is finished. I found it here.

dosomething(4, function () {
    console.log("finished loop");
});


function dosomething(delay, callback) {

    for (var i = 0; i < 100; i++) {
        $("body").append(i + "<br>");
    }
    alert("done");
    if (typeof callback == "function") callback();

}

FIDDLE

However, this will not work with functions that are asynchronous. I think that's the reason.

doAjax(4, function () {
    console.log("finished ajax");
});

function doAjax(delay, callback) {
    $.ajax({
        type: "post",
        url: "/echo/html/",
        data: {
            html: "some content",
            delay: 4
        },
        dataType: 'html',
        success: function () {
            console.log("ajax done");
        }
    });

    if (typeof callback == "function") callback();
}

FIDDLE

I know it is a bit silly to ask how to incorporate my own callback for an asynchronous request since jQuery has them built in and I just used one, but I was wondering how it could be achieved. Is it as complex as writing an entire promise library?

Community
  • 1
  • 1
1252748
  • 14,597
  • 32
  • 109
  • 229
  • A callback doesn't halt a script. A callback is just a piece of code that is not yet executed (because it's in a function). Only the function receiving the callback decides *when* (and *whether*) it gets executed. – Bergi Jan 29 '15 at 01:10
  • @Bergi I guess "postpone" execution is what I meant. – 1252748 Jan 29 '15 at 02:12
  • Also can you expound upon the reason "because it's in a function" please? Why does that make a difference? – 1252748 Jan 29 '15 at 02:17
  • By "because it's in a function" I meant that the code is not immediately evaluated, as it would when being put directly in the expression. You have to invoke the function to evaluate it. I hope I'm not confusing you more :-) – Bergi Jan 29 '15 at 02:51

1 Answers1

1

You aren't calling your callback after the request is done.


...
//HERE!
success: function(data){
  if (typeof callback == "function") callback(null, data);
},
error: callback
...
//NOT BELOW
Tracker1
  • 19,103
  • 12
  • 80
  • 106