2

I'm fairly new to the callback-style of programming in javascript. Is there a way to force code to wait until a function call finishes via a callback? Let me explain. The following function takes a number and returns a result based upon it.

function get_expensive_thing(n) {
  return fetch_from_disk(n);
}

So far, easy enough. But what do I do when fetch_from_disk instead returns its result via a callback? Like so:

function get_expensive_thing(n) {
  fetch_from_disk(n, function(answer) {
    return answer; // Does not work
  });
}

The above doesn't work because the return is in the scope of the anonymous function, rather than the get_expensive_thing function.

There are two possible "solutions", but both are inadequate. One is to refactor get_expensive_thing to itself answer with a callback:

function get_expensive_thing(n, callback) {
  fetch_from_disk(n, function(answer) {
    callback(answer);
  });
}

The other is to recode fetch_from_disk, but this is not an option.

How can we achieve the desired result while keeping the desired behaviour of get_expensive_thing -- i.e., wait until fetch_from_disk calls the callback, then return that answer?

2 Answers 2

2

Pretty much there's no "waiting" in browser Javascript. It's all about callbacks. Remember that your callbacks can be "closures", which means definitions of functions that "capture" local variables from the context in which they were created.

You'll be a happier person if you embrace this way of doing things.

Sign up to request clarification or add additional context in comments.

2 Comments

Even if you could wait, you are asking for a non-responsive browser by doing that.
That's fair enough. My purpose here was to establish for sure that it's actually impossible to create a function that returns a value that it obtained via a callback.
0

add in that missing return :)

function get_expensive_thing(n) {
  return fetch_from_disk(n, function(answer) {
    return answer;
  });
}

2 Comments

Maybe I didn't make this clear: in that example, fetch_from_disk had changed its behaviour to instead return the result via a callback. So its return value is actually undefined.
you made it clear, yet many people also return the result of the callback too, think of fetch_from_disk(n,c) { return c(val) } - apologies if this was noise :)

Your Answer

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.