2017-01-30 122 views
-1

怎么在我的.then()printer.done()不显示我的消息?。然后()与承诺订购

printer.done()应该显示一个消息模板。

.then(() => { 
    const whileHeapList =() => { 
     setTimeout(() => { 
      console.log(new Date()); 
      console.log(1); 
      setTimeout(() => { 
       console.log(2); 
       console.log(new Date()); 
      }, 5000) 
     }, 5000); 
    }; 
    whileHeapList(); 
    }).then(() => { 
     printer.done() 
    }); 

我想我的代码做的是日志1,等待5秒钟登录2,然后打印出printer.done()模板消息什么

眼下是这样的输出:

** TEMPLATE ** 

2017-01-30T04:19:54.111Z 
1 
2 
2017-01-30T04:19:59.118Z 
+2

你的代码在上面'.then'没有按” t返回一个等待的承诺,因此,'printer.done'将立即执行 –

+0

@JaromandaX如果我有'返回新的Promise(whileHeapList)'而不是'whileHeapList()'我得到1,2和时间日志,但该模板不显示 – Liondancer

回答

1

如果你希望第二个.then等待第二个setTimeout完成,你需要返回第一个.then的承诺,该第一个承诺解决第二个setTimeout触发

.then(function() { 
    var whileHeapList = function whileHeapList() { 
     return new Promise(function(resolve) { // added 
      setTimeout(function() { 
       console.log(new Date()); 
       console.log(1); 
       setTimeout(function() { 
        console.log(2); 
        console.log(new Date()); 
        resolve(); // added 
       }, 5000); 
      }, 5000); 
     }); // added 
    }; 
    return whileHeapList(); // added a return 
}).then(function() { 
    printer.done(); 
}); 

,或者使用侑评论未遂代码

.then(function() { 
    var whileHeapList = function whileHeapList(resolve) { 
     setTimeout(function() { 
      console.log(new Date()); 
      console.log(1); 
      setTimeout(function() { 
       console.log(2); 
       console.log(new Date()); 
       resolve(); // added 
      }, 5000); 
     }, 5000); 
    }; 
    return new Promise(whileHeapList); 
}).then(function() { 
    printer.done(); 
}); 
+0

我试过这个,但模板首先被打印,然后剩下的。我试图首先打印1,2'和Date(),然后是模板。不知道为什么会发生= /。我认为最后一个'.then()'只有在'.then()'完成之前才会执行' – Liondancer

+0

这段代码将会记录1,2,然后才会执行'printer.done()'...确保你不会在代码中使用**每个返回** - 问题可能存在,因为你发布的代码与你实际使用的代码有很大的不同 - 因为代码中的嵌套超时没有任何用处......如果你想要然后在之前的“.then”中“等待”一些异步代码,你必须返回一个Promise来解析异步完成 –

0

我会做一个睡眠功能和链然后

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); 

...  

.then(() => sleep(5000)) 
.then(() => console.log(1, new Date())) 
.then(() => sleep(5000)) 
.then(() => console.log(2, new Date())) 
.then(() => printer.done())