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?

asked Jan 29, 2015 at 0:40
4
  • 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. Commented Jan 29, 2015 at 1:10
  • @Bergi I guess "postpone" execution is what I meant. Commented 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? Commented 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 :-) Commented Jan 29, 2015 at 2:51

1 Answer 1

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
answered Jan 29, 2015 at 0:42
Sign up to request clarification or add additional context in comments.

1 Comment

I don't really understand what you mean by this answer.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.