skip to Main Content
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


  1. Instead of calling the callback function directly inside the first function, you can pass the the function as an argument into the hello function and then call it inside the setTimeout.

    first(second);
    
    function first(callback) {
       hello(callback);
    }
    
    function second(){
       goodbye(); 
    }
    
    function hello(callback) {
       setTimeout(() => {
          console.log('Hello');
          callback();
       }, 3000);
    }
    
    function goodbye() {
       console.log('Goodbye');
    }
    

    You could also use a Promise and await. You could read more about it here

    async function first(callback) {
      await hello();
      callback();
    }
    
    function second(){
      goodbye(); 
    }
    
    function hello() {
      return new Promise(resolve => {
        setTimeout(() => {
            console.log('Hello');
            resolve();
        }, 3000);
     });
    }
    
    function goodbye() {
       console.log('Goodbye');
    }
    
    first(second);
    
    Login or Signup to reply.
  2. You could use an async method and the then method to order the executions.

    async function hello() {
        await setTimeout(() => {
            console.log('Hello');
        }, 3000);
    }
    
    function first(callback) {
        hello().then(
           callback();
        );
        
    }
    

    Essentially this creates a promise object that and then waits for that promise to be resolved before executing the following code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search