views:

33

answers:

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  A: 

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.

Pointy
Even if you could wait, you are asking for a non-responsive browser by doing that.
JohnFx
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.
eegg
A: 

add in that missing return :)

function get_expensive_thing(n) {
  return fetch_from_disk(n, function(answer) {
    return answer;
  });
}
nathan
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`.
eegg
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 :)
nathan