javascript - ES6 Promise中then方法不执行
本文介绍了javascript - ES6 Promise中then方法不执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
为什么then中的回调函数不会执行呢
<body>
<div class = "ball ball1" style="margin-left:0;"></div>
<div class = "ball ball2" style="margin-left:0;"></div>
<div class = "ball ball3" style="margin-left:0;"></div>
</body>
<script type="text/javascript">
var ball = document.getElementsByClassName("ball");
var ball1 = ball[0];
var ball2 = ball[1];
var ball3 = ball[2];
function animate (ball, distance){
return new Promise(function(resolve, reject){
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";
}
animate(ball, distance);
},13)
})
animate(ball,distance);
};
animate(ball1,100).then( () => animate(ball2, 200)
).then( () => animate(ball3, 300)
).then( () => animate(ball3, 150)
).then( () => animate(ball2, 150)
).then( () => animate(ball1, 150)
);
</script>
可以打印出resolve,但就是不执行then中的内容,为什么呢
解决方案
看你的代码是想用递归判断,如果到达某个距离就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);
})
};
这篇关于javascript - ES6 Promise中then方法不执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文