first(second);
function first(callback) {
hello();
callback();
}
function second(){
goodbye();
}
function hello() {
setTimeout(() => {
console.log('Hello');
}, 3000);
}
function goodbye() {
console.log('Goodbye');
}
I’m looking to find a way in Javascript where the second function runs only after the first function is fully completed without knowing how long it would take. I purposely put a timeout in Hello function to test this behavior. The duration of this timeout can range from a few seconds to a few minutes.
2
Answers
Instead of calling the
callback
function directly inside thefirst
function, you can pass the the function as an argument into thehello
function and then call it inside thesetTimeout
.You could also use a
Promise
andawait
. You could read more about it hereYou could use an async method and the then method to order the executions.
Essentially this creates a promise object that and then waits for that promise to be resolved before executing the following code.