Search code examples
javascriptasynchronousasync-awaitpromise

Javascript: how to get one function to run after another completes


I'm new to javascript and promises. I'm trying to get one function not to start running until the first function has completed.

In this case, I want the "dontDoUntilDelayIsComplete" function to run AFTER the "delayGreet" function.

function delayGreet() {
    setTimeout(greet, 1000);
}

function greet() {
    para1.textContent = "Hi there!";
}

function createPromise() {
    return new Promise((resolve) => resolve(delayGreet));
}

function dontDoUntilDelayIsComplete() {
    para2.textContent = "Please dont do before";
}

function callMethod() {
    createPromise().then(dontDoUntilDelayIsComplete);
}

callMethod();`

I've tried putting the functions within a promise and use the .then() method. However, I'm unable to get it to work.


Solution

  • I don't think this is accurate:

    "I want the "dontDoUntilDelayIsComplete" function to run AFTER the "delayGreet" function"

    I think you want dontDoUntilDelayIsComplete to run after greet, which is different.

    setTimeout does not create a promise, it simply schedules a function to run. If you want something to run immediately after that, then schedule that as well.

    function greet() {
        console.log("Hi there!");
    }
    
    function dontDoUntilDelayIsComplete() {
        console.log("Please dont do before");
    }
    
    function delayGreet() {
        function greetThenDoSomethingElse() {
          greet();
          dontDoUntilDelayIsComplete();
        }
        setTimeout(greetThenDoSomethingElse, 1000);
    }
    
    delayGreet();


    Here's a solution with a generic callback:

    function greet() {
        console.log("Hi there!");
    }
    
    function dontDoUntilDelayIsComplete() {
        console.log("Please dont do before");
    }
    
    function delayGreetThenCallback(callback) {
        function greetThenCallback() {
          greet();
          callback();
        }
        setTimeout(greetThenCallback, 1000);
    }
    
    delayGreetThenCallback(dontDoUntilDelayIsComplete);


    And here's one with a promise:

    function greet() {
      console.log('Hi there!');
    }
    
    function dontDoUntilDelayIsComplete() {
      console.log('Please dont do before');
    }
    
    function delayGreet() {
      return new Promise((resolve) =>
        setTimeout(() => {
          greet();
          resolve();
        }, 1000)
      );
    }
    
    delayGreet().then(dontDoUntilDelayIsComplete);