gpt4 book ai didi

JavaScript - 减慢循环速度

转载 作者:行者123 更新时间:2023-12-01 04:01:13 25 4
gpt4 key购买 nike

我在 Controller 中有这些代码,它们使用 $http get 调用 Web 服务来检索一些数据。以下是代码:

更新代码:

   var boolGetBoothCoords = false;
BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3)

.then(function(response) {
var data = response.data
console.log('data', data.arrBoothDesignatedCoords)
boothDesignatedCoords = data.arrBoothDesignatedCoords;
boolGetBoothCoords = true;
})

console.log("boothDesignatedCoords ", boothDesignatedCoords ); // undefined
// And a lot of other codes

但是,由于 $http get 是异步方法,程序将调用控制台日志以及紧随其后的代码,并且 BoothDesignatedCoords 将是未定义的。我不要那个。我希望程序仅在 Web 服务消耗完成后调用控制台日志和代码。所以我使用这个答案做了以下操作:how to slow down a javascript loop :

    go();
function go() {
console.log("hello");

if (boolGetBoothCoords == false) {
setTimeout(go, 1000);

}
else
{

}
}
go()

console.log("boothDesignatedCoords ", boothDesignatedCoords ); // undefined
// OTHER CODES that uses variable boothDesignatedCoords will be undefined as well

但是,我不知道为什么尽管使用了这种方法,它仍然会调用控制台日志,但Web服务消费尚未完成。有人可以帮帮我吗?谢谢。

最佳答案

setTimeout是异步的,所以实际上你调用 go 并没有真正发挥作用。功能。

将会发生的是:

  • 调用 go()功能
  • 调用 setTimeout在函数内部 - 将安排 go (大约)1 秒内被调用
  • 调用 console.log之后立即

您可能想要的是将您的 console.logthen像这样的回调:

var boolGetBoothCoords = false;
BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3)
.then(function(response) {
return response.data.arrBoothDesignatedCoords;
})
.then(function(boothDesignatedCoords) {
console.log("boothDesignatedCoords ", boothDesignatedCoords );
});

<小时/>

另一个选项(不推荐)是输入 console.logelse if的一部分您的 go 中的声明功能。

在这种情况下,您还应该定义 boothDesignatedCoords在整个代码片段之前。

关于JavaScript - 减慢循环速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42174649/

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