繁体   English   中英

JavaScript异步示例不起作用

[英]Javascript async example doesn't work

我正在尝试es6 promise并将它们链接起来,但不明白为什么我的示例不起作用。

我想多次链接printInterval()和setInterval(),并希望_interval像这样减少:

  • 等待3000毫秒显示此消息
  • 将间隔设置为2000
  • 等待2000毫秒显示此消息
  • 将间隔设置为1000
  • 等待1000毫秒显示此消息
  • 设置间隔为500
  • 等待500毫秒显示此消息

但我得到以下内容:

  • 等待3000毫秒显示此消息
  • 将间隔设置为2000
  • 将间隔设置为1000
  • 设置间隔为500
  • 等待500毫秒显示此消息
  • 等待500毫秒显示此消息
  • 等待500毫秒显示此消息

function printInterval() {
    return new Promise(function(resolve, reject){
        setTimeout(function () {
            console.log('waited ' + _interval + 'ms to display this message')
            resolve(_interval);
        }, _interval)
    })
}

function setInterval(interval){
    return new Promise(function(resolve, reject) {
        setTimeout(function () {
            console.log('setting interval to ', interval)
            _interval = interval;
            resolve(_interval);
        }, 0);
    })
}

var _interval = 3000;

printInterval()
.then(function(){setInterval(2000)})
.then(function(){printInterval()})
.then(function(){setInterval(1000)})
.then(function(){printInterval()})
.then(function(){setInterval(500)})
.then(function(){printInterval()});

谢谢!

您应该return这些函数,而不仅仅是调用它们:

printInterval()
.then(function(){return setInterval(2000)})
.then(function(){return printInterval()})
.then(function(){return setInterval(1000)})
.then(function(){return printInterval()})
.then(function(){return setInterval(500)})
.then(function(){return printInterval()});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM