gpt4 book ai didi

Javascript 异步示例不起作用

转载 作者:行者123 更新时间:2023-11-30 16:47:45 25 4
gpt4 key购买 nike

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

我想多次链接 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()});

谢谢!

最佳答案

你应该返回那些函数而不仅仅是调用它们:

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

关于Javascript 异步示例不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30980988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com