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();
}
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();
}
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?
-
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– Bergi2015年01月29日 01:10:28 +00:00Commented Jan 29, 2015 at 1:10
-
@Bergi I guess "postpone" execution is what I meant.1252748– 12527482015年01月29日 02:12:05 +00:00Commented Jan 29, 2015 at 2:12
-
Also can you expound upon the reason "because it's in a function" please? Why does that make a difference?1252748– 12527482015年01月29日 02:17:52 +00:00Commented Jan 29, 2015 at 2: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– Bergi2015年01月29日 02:51:33 +00:00Commented Jan 29, 2015 at 2:51
1 Answer 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
1 Comment
Explore related questions
See similar questions with these tags.