javascript - setTimeout 函数完成后调用 Promise

标签 javascript node.js

我正在尝试在我的代码中实现 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);
        }
    }
}

最佳答案

使用一组 Promise,其中每个resolve() 都在 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')
     });    
}

关于javascript - setTimeout 函数完成后调用 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53354887/

相关文章:

javascript - 我怎样才能重新开始 offset();反复发挥作用

node.js - 如何检测和测量 node.js 中的事件循环阻塞?

javascript - Backbone JS : Assign a model attribute in fetch call

javascript - 获取每一行文本元素

unit-testing - Node assert.throws 未捕获异常

javascript - OrientJS 中的连接池

performance - Node js 在 60 个连接上性能缓慢

javascript - node.js - 重定向到中间件中的另一个网址

javascript - 通过 Couchdb 中的更新处理程序添加 id 和 author 字段

javascript - NodeJS HTTP请求未按顺序执行