setTimeout函数完成后调用Promise

时间:2018-11-17 19:42:25

标签: 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);
        }
    }
}

2 个答案:

答案 0 :(得分:2)

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

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')
     });    
}

答案 1 :(得分:1)

您的.then处理函数从未被调用的原因是,promise停留在初始状态,即“待处理”。

承诺可以待定或已解决(已实现/已拒绝)。传递给Promise构造函数的回调有两个参数,resolve(触发实现)和reject(触发拒绝)。

var promise1 = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo');
  }, 300);
});

promise1.then(function(value) {
  console.log(value);
  // expected output: "foo"
});

the MDN docs for the Promise API处查看上述代码的来源。

我认为上面的示例为您提供了有关如何实现基于承诺的延迟的提示,但如果您需要进一步的帮助,请告诉我。