-1

I am coding at JavaScript.
I have two functions func1, func2.
func1 doesn't have return value and func2 has return value.

function outFunc(){
    func1();
    val = func2();
    return val;
}

func1 has asynchronous operation inside.
How can I ensure that func2 is called only after func1 has completed?

Larry Lu
  • 1,609
  • 3
  • 21
  • 28

2 Answers2

1

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.

Community
  • 1
  • 1
David
  • 208,112
  • 36
  • 198
  • 279
1

You won't be able to return value from func2. Your outFunc will also have a callback handler if you want to use value returned by func2 outside.

function outFunc(finalCallback){
    func1(func2,finalCallback);
}

function func1(callback, finalCallback)
{
 //once the asynch operation has finished
 callback(finalCallback);
}

function func2(finalCallback)
{
   //compute return-value
   finalCallback(return-value);
}
gurvinder372
  • 66,980
  • 10
  • 72
  • 94