我的.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
答案 0 :(得分: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();
});
答案 1 :(得分: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())