I have several functions that call each other asyncronously, and I need to catch a situation when last functionis called.
await statement supposes to call a function I should wait, but it is not to be called directly
function First(){
console.log('First is called');
setTimeout(Second(), 1000);
return;
}
function Second(){
console.log('Second is called');
}
function Main(){
First();
console.log('I called First and I want that Second also is complete');
}
I try to use await, but the problem is that I need to call function First() but should wait until Second is called. And including await in every call seems to be too complicated, since the chain length is quite large.
The solution could be an infinite loop in Main until Second initiate a variable, but I feel there should be more clear solution.
2
Answers
you can use Promises. In your case, you can modify your First and Second functions to return Promises. This way, you can await the completion of Second without having to call it directly.
like this
If you have a long chain of asynchronous functions where each function calls the next, you can still use Promises effectively.
if this is what do you mean by catching the last one
If you don’t want to use Promises for some reason (or if the example provided doesn’t fully illustrate the problem), perhaps you’re looking for a custom event?
Your "second" operation can emit a custom event, and anything listening for that event can respond accordingly. For example: