2017-02-11 196 views
0

我在调用web服务的控制器中使用$ http get来检索一些数据。这是下面的代码:JavaScript - 减速循环

UPDATE码

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服务消费还没有完成,尽管使用这种方法。有人可以帮帮我吗?谢谢。

+0

为什么不在'fnProceedOtherTask1()'调用的最后'then'回调中包含'console.log'? – andrusieczko

+0

对不起,感到困惑。我仍然更新了我的问题 – Antoni

+0

,最好在最后一次回调中打印它比等待使用'setTimeout'更好...如果服务器响应时间超过1秒会发生什么?它仍然是undefined – andrusieczko

回答

1

setTimeout是异步的,所以实际上你真的没有区别,调用go函数。

会发生什么事是:

  • 通话go()功能
  • 通话setTimeout里面的功能 - 这将安排go在(大约)1S
  • 电话console.log
之后立即调用

你可能想要的是把你的console.log拨打then致电回到这样的:

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


其他选项(不推荐)将是把console.logif声明else部分在go功能。

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

+0

嗨,但如果我按照你的代码还有另一个问题。之前。然后(函数(boothDesignatedCoords)方法被调用,程序已经退出控制器 – Antoni

+0

我想你正在使用AngularJS,你想改变'$ scope'...那么我建议你应该在回调中对其进行所有更改 – andrusieczko

1

假设在响应后运行的代码应在响应之后调用。

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; 
    codeThatUsesTheResponseData(); 
}); 
function codeThatUsesTheResponseData() { 
    console.log("boothDesignatedCoords ", boothDesignatedCoords); // undefined 
    // And a lot of other codes 
} 
+0

嗨,但如果我遵循你的代码,还有另一个问题。在调用CodeThatUsesTheResponseData方法之前,程序已经退出控制器 – Antoni

+0

它会在哪个行后退出?在某些时候应该有一个返回,异常或刷新,以使代码不会调用下一行。 –