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?