首页 > 解决方案 > setTimeout 函数完成时调用 Promise

问题描述

我正在尝试在我的代码中实现 Promise 语句,并希望得到一些帮助。我有一个使用 setTimeout 运行的函数。我想在完成后调用一个函数。

尝试包括 Promise 语句,但我觉得我做的不正确。任何反馈都是有帮助的

function App(){

        let exampleProm = new Promise(
            function(){
                    type.type("hello , dexter", 100);
            }
        ).then(console.log('finished'));

}

App();

//首先被调用的代码

module.exports = {
    type: function(phrase, delaySpeed){
        let total = 0;
        let empty = [];
        for(let i = 0; i < phrase.length;i++){
            total += delaySpeed;
            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
                }
            },total);
        }
    }
}

标签: javascriptnode.js

解决方案


使用每个 resolve() 内部的 promise 数组,setTimeout()然后Promise.all()在它们全部解析后运行代码

module.exports = {
  type: 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()
  }
}

function App(){    
     type.type("hello , dexter", 100).then(function(){
         // this then() fires when the Promise.all() resolves
         console.log('finished')
     });    
}


推荐阅读