繁体   English   中英

承诺和setTimeout不能一起工作

[英]Promises and setTimeout is not working together

我一直在为此而苦苦挣扎。 我有一个推荐滑块。 没什么花哨的,但我想在元素中添加过渡类2秒钟,然后将其删除。

另外,我正在使用这种项目来使自己更加努力。 因此,我尝试使用Promises进行操作,并且推荐来自Fetch电话。

由于某些原因, setTimeout根本无法工作。 调试器表示无需计时器即可解决该问题。

     arrows.forEach((item) => {
        item.addEventListener('click',() => {
            return new Promise ((resolve,reject) => {
                container.classList.add('transition');
                setTimeout(() => {      
                    if (item.getAttribute('data-direction') == 'right'){
                        if(counter < array.length -1) {
                            counter ++;
                        } else {
                            counter = 0;
                        }
                    } else {
                        if(counter > 0) {
                            counter --;
                        } else {
                            counter = array.length -1;
                        }
                    }
                }, 5000)                
            }).then(resolve =>{
                testi(array,counter);
                container.classList.remove('transition');
            })
        });
    })

您需要在setTimeout()调用resolve() setTimeout()

  arrows.forEach((item) => {
        item.addEventListener('click',() => {
            // no point in returning to an event listener
           new Promise ((resolve,reject) => {
                container.classList.add('transition');
                setTimeout(() => {      
                  /// do synchronous stuff

                  // then reolve promise
                  resolve()// include any value you want passed to next `then()`
                }, 5000)                
            }).then(resolve =>{
                testi(array,counter);
                container.classList.remove('transition');
            })
        });
    })

在您的代码中:

return new Promise ((resolve,reject) => {
                container.classList.add('transition');
                setTimeout(() => {      
                    if (item.getAttribute('data-direction') == 'right'){
                        if(counter < array.length -1) {
                            counter ++;
                        } else {
                            counter = 0;
                        }
                    } else {
                        if(counter > 0) {
                            counter --;
                        } else {
                            counter = array.length -1;
                        }
                    }
                }, 5000)   
              })

您不是在解决或拒绝诺言。 因此,promise始终处于待处理状态,并且您的then() (或在发生错误的情况下, catch() )方法回调将永远不会执行。

这是一个例子:

 let prom = new Promise ((resolve,reject) => { setTimeout(() => { resolve('succes!') }, 5000) }); prom.then((res) => {console.log(res); }); 

暂无
暂无

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

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