【发布时间】:2014-11-01 20:13:47
【问题描述】:
我的项目有问题。
为了描述这个问题,我写了简化的代码sn-p:
function waitFor(fnReady, fnCallback) {
var check = function() {
if (fnReady()) {
fnCallback();
}
else {
setTimeout(check, 100); // wait another 100ms, and try again
}
};
check();
}
var result = 0;
var flag = true;
function ajaxRequest() {
setTimeout(
function() { flag = false;
console.log('ping');
},3000
);
}
function ajaxRequestHandler() {
setTimeout(
function() { flag = true;
console.log('pong');
}, 200
);
}
for(var i =0;i<10; i++){
waitFor(function() { return flag; }, ajaxRequest);
waitFor(function() { return !flag; }, ajaxRequestHandler);
}
它返回:
ping - 10 times
pong - 10 times
想要的结果:
ping
3 second timeout
ping
---------------------
ping
3 second timeout
pong
--------------------
.....
您能帮我更正我的代码吗?
更新
实际问题:
我有一张谷歌地图。
我有很多地方需要重画。
如果我发送非常重要的应用程序逻辑
request1
request2
request3
request4
我应该按这个顺序处理响应
handle response of request1
handle response of request2
handle response of request3
handle response of request4
我不知道请求顺序的问题。
在文件的不同位置,我看到以下代码行:
google.maps.event.addListener(searchBox, 'bounds_changed', renderTerminalsOnMapAndFitBounds);
...
$.getJSON('getAllTerminals.json', renderTerminalsOnMapAndFitBounds);
.....
$.getJSON('getAllTerminalsInsideRectangle.json', renderTerminalsOnMapAndFitBounds);
...
$.getJSON('getAllTerminalsInsideCircle.json', renderTerminalsOnMapAndFitBounds);
...
$.getJSON('getBigTerminals.json', renderTerminalsOnMapAndFitBounds);
........
renderTerminalsOnMapAndFitBounds 方法向服务器发送请求,并在地图上成功替代渲染结果。但是这个事件经常发生
【问题讨论】:
-
这与您之前的问题有什么不同:stackoverflow.com/questions/26691226/…? JS 中的异步行为不应该通过轮询来完成。它应该通过利用已经提供的完成回调来完成。此外,这些问题可能会更好地成为具有真实代码的真实用例,而不是您将它们表述为理论讨论的方式。
-
我的问题得到了正确答案,但我不能在我的实际应用程序中使用这种方式
-
现在我正在尝试不要使用延迟。
-
然后,向我们展示您遇到的实际问题,而不是一些理论讨论。只有这样,我们才能为您的实际问题提供最佳解决方案。我坚持我的意见,即轮询异步事件的完成不是编写异步代码的正确方法。如果您不想使用 Promise,请使用完成回调。
-
不,我不清楚。请编辑您的问题以包含对此实际问题的更详细描述。只有这样,您才能充分利用这里的帮助。
标签: javascript jquery synchronization