Code always executes in the order in which it's processed.
However, if func1
is internally performing an asynchronous operation, then that is going to invoke something outside of the code which doesn't return immediately. func1
itself will complete, but the operation might not.
In that case, func1
should expose as a function parameter a callback. Which internally to func1
would be structurally, intuitively similar to this:
function func1(callback) {
// do some stuff
callback();
}
Now, in do some stuff
there would be asynchronous operations which have the same caveat, so func1
would have the responsibility of passing along the callback
appropriately into those operations as needed. The structure of this depends on what those operations are, really.
But the point is that any function which performs an asynchronous operation should expose a callback to be invoked after that operation completes. Then you'd use it as:
func1(func2);
Note however that you run into another problem here. Because func1
is asynchronous, so is outFunc
. Which means this isn't going to work:
return val;
outFunc
is going to complete before the asynchronous operation(s) complete. So nothing of value will be returned. There are some really good in-depth explanations on this highly-linked question. But essentially you're going to need to re-think how you're structuring your code. And the contrived example provided in the question doesn't really lend itself to advice on that.
Instead of returning values, you need to provide callbacks. The code which would normally use the returned value to perform some operation would instead be put into the callback and perform that operation at a later time when the value becomes available.