给出:一个用于解析网站上部分数据的 php 脚本。它解析大约 10k 个产品,因此速度相当慢。
我需要用 html/css/js 制作一个 Web 前端。我做了一个循环,它发出 ajax 请求并显示进度信息。它使用同步ajax,因为它需要等待另一个请求完成才能执行另一个请求。
do {
var parseProductsActive = true;
var counter = 0;
myAjax('parseProducts.php?start='+counter, false, function(resp) {
if (resp[0]=='s') {
counter += Number(resp.substring(1));
parseProductsActive = false;
}
else {
counter += Number(resp);
}
self.postMessage(counter);
});
} while (parseProductsActive==true);
我在 Web Worker 中执行此操作,因为我担心它会因为这种无限循环而挂起界面,并且 ajax 本身的同步性无助于解决问题。
但是当我尝试在 Web Worker 中使用 ajax 时,我发现这很困难,尽管可能,因为 jQuery 根本无法在 Web Worker 中工作。即使对于非 DOM 操作,它也使用 DOM,并且 DOM 在 Web Worker 中不可用。许多开发人员根本怀疑是否使用 Web Workers。我只是想问一下我这样做是对还是错。还有其他我看不到的表面解决方案吗?
最佳答案
您猜对了:递归回调是按顺序执行一堆异步请求的方法。它可能看起来有点像这样:
var parseProductsActive = true;
var counter = 0;
//define the loop
function doNextAjax(allDone){
//Instead of just returning, an async function needs to
//call the code that comes after it explicitly. Receiving a callback
//lets use not hardcode what comes after the loop.
if(!parseProductsActive){
allDone();
}else{
//use async Ajax:
myAjax('parseProducts.php?start='+counter, true, function(resp) {
if (resp[0]=='s') {
counter += Number(resp.substring(1));
parseProductsActive = false;
}
else {
counter += Number(resp);
}
self.postMessage(counter);
doNextAjax(); // <---
});
}
//Start the loop
doNextAjax(function(){
console.log("the code that runs after the loop goes here")
});
//BTW, you might be able to get rid of the "parseProductsActive" flag with a small
// refactoring but I'm keeping the code as similar as possible for now.
//It would be kind of equivalent to writing your original loop using a break statement.
是的,它丑陋且冗长,但 ints 是在原始 Javascript 中执行此操作的唯一方法。如果您想编写一个看起来像循环的结构化版本,而不是带有大量 goto 的版本,请查看异步控制流库之一或将具有异步支持的 JavaScript 扩展编译回常规 JS 的编译器之一带回调。
关于javascript - 我是否需要 Web Workers 来循环 AJAX 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21586863/