[英]Do I need Web Workers for looping AJAX-requests?
給定:用於解析網站上的部分數據的php腳本。 它解析大約1萬個產品,因此速度很慢。
我需要使用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中進行此操作,因為由於這種無休止的循環,恐怕它將掛斷接口,而且(a)ajax本身的同步性無助於解決問題。
但是,當我嘗試在Web Worker中使用Ajax時,我發現雖然很難,但因為jQuery根本無法在Web Worker中使用。 它甚至對非DOM操作也使用DOM,而Web Worker中不提供DOM。 許多開發人員完全懷疑使用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.
是的,它丑陋而冗長,但是它是用原始Javascript做到這一點的唯一方法。 如果您想編寫一個看起來更像循環的結構化版本,而不是帶有大量的goto,請查看其中一個異步控制流庫或一個將帶有異步支持的Javaascript擴展編譯回常規JS的編譯器之一與回調。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.