javascript - ES6 Promise中then方法不执行
PHP中文网
PHP中文网 2017-04-11 12:58:34
[JavaScript讨论组]

为什么then中的回调函数不会执行呢


    

可以打印出resolve,但就是不执行then中的内容,为什么呢

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(2)
天蓬老师

看你的代码是想用递归判断,如果到达某个距离就resolve。但是有一个问题,每次递归都返回一个 new promise是全新的,与最开始的那个promise没有任何关系,所以第一个promise永远不会被resolve
解决办法很简单,保持引用一个promise就行了。

function animate (ball, distance){
        return new Promise(function(resolve, reject){
            function timeout(ball,distance){ //再加个函数包裹递归就不会影响Promise
                setTimeout(function(){
                    let marginLeft = parseInt(ball.style.marginLeft);
                    if(marginLeft === distance){
                        console.log("resolve")
                        resolve();
                    }else{
                        if(marginLeft < distance){
                            marginLeft++;
                        }else{
                            marginLeft--;
                        }
                        ball.style.marginLeft = marginLeft+"px";
                        timeout(ball, distance);
                    }
                },13)
            }
            timeout(ball,distance);
        })
    };
阿神

不解释,看代码:


    function animate (ball, distance){
        return new Promise(function(resolve, reject){
            function ant() {
                let marginLeft = parseInt(ball.style.marginLeft);
                if(marginLeft === distance){
                    console.log("resolve");
                    resolve();
                }else{
                    if(marginLeft < distance){
                        marginLeft++;
                    }else{
                        marginLeft--;
                    }
                    ball.style.marginLeft = marginLeft+"px";
                    start();
                }
            }

            function start() {
                setTimeout(function(){
                    ant();
                },13)
            }

            start();
        })
    };
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号