NodeJS - Run function once setTimeout is complete

231 views Asked by At

Working on a project where I call multiple functions featuring setTimeout. In the below code, I can't seem to get my code to run in order. For example, call one function, then the next, then the next. With each waiting for the other to finish.

Feel free to change my code, as I would love to learn more regarding the matter.

**UPDATE

Since it was tough to explain my problem, I figured I'll just post the full code. In the greet page, I ask prompt the user a question using inquirerJS. When I ask the user, my third function fires off, without waiting for the promise to resolve.

TYPE PAGE

module.exports = {
  writer: function(phrase, delaySpeed) {
    let total = 0;
    let empty = [];
    let promises = []
    for (let i = 0; i < phrase.length; i++) {
      total += delaySpeed;
      // new promise for each character
      let promise = new Promise(function(resolve, reject) {
        setTimeout(() => {
          empty.push(phrase.charAt(i));
          process.stdout.write(chalk.blue.bold(empty[i]));
          if (empty.length === phrase.length) { //if complete
            process.stdout.write('\n'); //puts on separate line
          }
          // assuming above writes are synchronous can now resolve promise
          resolve()
        }, total);

      });
      // push new promise to array
      promises.push(promise)
    }
    // return the all() promise
    return Promise.all(promises)// add another then() if you need to return something to next then() in App()
  }
}

GREET PAGE


const inquirer = require('inquirer');
let intro = require('./type.js');
let chalk = require('chalk');
let type = require('./type.js');

let greet = function(){
    let questions = [{
        type: 'input',
        name: 'firstName',
        message: 'what your name',
    }];

    inquirer
        .prompt(questions)
        .then(answers => {
            setTimeout(function(){
                type.writer(`Hello ${answers.firstName}`,100);
            },500);
        }
    )
}
module.exports = greet;

MAIN APP PAGE

let initialGreeting = require('./user.js');



function App(){
    function second(){
        return new Promise(function(resolve,reject){
            setTimeout(function a(){
                initialGreeting();
                 resolve();
             }, 200);
        }
    )
function third(){
    console.log('finished')
}
    type.writer('abc',100).then(second).then(third);

};

App();

1

There are 1 answers

0
AlbertS On BEST ANSWER

Return you new Promise:

let greet = function(){
    let questions = [{
        type: 'input',
        name: 'firstName',
        message: 'what your name',
    }];
    inquirer
        .prompt(questions)
        .then(answers => {
            return new Promise(function(resolve,reject) {
                setTimeout(function(){
                    type.writer(`Hello ${answers.firstName}`,100);
                    resolve();
                },500);
            }).then(function(){
                console.log("run after")
            });

        }
    )
}
module.exports = greet;