NodeJS-setTimeout完成后运行功能

时间:2018-11-19 04:42:21

标签: javascript node.js inquirerjs

在一个项目中,我调用了多个具有setTimeout功能的函数。在下面的代码中,我似乎无法使我的代码按顺序运行。例如,调用一个函数,然后调用下一个,再调用下一个。彼此等待对方完成。

请随时更改我的代码,因为我想了解更多有关此问题的信息。

**更新

由于很难解释我的问题,所以我认为我将发布完整的代码。在“欢迎”页面中,我使用InquirerJS提示用户一个问题。当我询问用户时,我的第三个功能会触发,而无需等待承诺解决。

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 个答案:

答案 0 :(得分:1)

返回新的承诺:

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;