如何按顺序循环 GET/POST 个调用(等待上一个)return?

How to loop through GET/POST calls sequentially (waiting for previous) return?

我正在为网页编写 Tampermonkey 脚本并尝试从其他页面提取数据。
我正在尝试制作一个函数,该函数内部有一个循环,通过列表 llcList,并从 ajax 方法 GET 中检索数据,但我想等待完成一个请求,然后再转到第二个.
如果我能让它多等一段时间,那就更好了。

应该发生什么:

  1. 发送对 llcList 的请求[0]
  2. 获取return数据,对其进行处理
  3. 稍等片刻
  4. 发送对 llcList[1] 的新请求

这可能吗?我尝试了几种方法,每次循环发送所有请求而不是一秒钟。 :

function F_Company_LLC(){
for (i = 0; i < llcList.length;i++) {
        if(llcList[i][2]=="lab"){
            //run function 0
            //break;
        }
        else if(llcList[i][2]=="shop"){
            //run function 1
            //break;
        }
        else{
            F_GET_CompData(llcList, llcList[i][1],i,function(result){
                console.log(result);
            });
        }
}}

function F_GET_CompData(F_GET_CompData_list, CompID, F_GET_CompData_row, callback){
$.ajax({
    method : "GET",
    url: base_link+"/company/edit_company/"+CompID,
    beforeSend: function(){runningRequest++;},
    success: function(data){

  //data processing

        runningRequest--;
    },
    error: function() {console.log("Get_ComData");}
});
callback(runningRequest);}

这是一个常见的场景。请注意,通常没有必要按顺序处理调用。通常只需发送带有 ajax 调用的上下文并将所有内容拼凑在一起,因为它是半随机的,如 .

所示

强制顺序行为的一种方法是通过 complete 函数进行链式调用。这是演示该过程的 功能齐全的代码 。要使用,请在 Stack Overflow 页面上将其粘贴到浏览器控制台。 :

var listO_pages = ["q/48/", "q/27/", "q/34/", "q/69/", "badpage"];
var numPages    = listO_pages.length;

getPageN (0);  //-- Kick off chained fetches

function getPageN (K) {
    if (K >= 0  &&  K < numPages) {
        let targPage = listO_pages[K];

        $.ajax ( {
            url:            "https://whosebug.com/" + targPage,
            context:        {arryIdx: K},  //  Object Helps handle K==0, and other things
            success:        processPage,
            complete:       finishUpRequest,
            error:          logError
        } );
    }
}

function processPage (sData, sStatus, jqXHR) {
    //-- Use DOMParser so that images and scripts don't get loaded (like jQuery methods would).
    var parser          = new DOMParser ();
    var doc             = parser.parseFromString (sData, "text/html");
    var payloadTable    = doc.querySelector ("title");
    var pageTitle       = "Not found!";
    if (payloadTable) {
        pageTitle       = payloadTable.textContent.trim ();
    }
    var [tIdx, tPage]   = getIdxAndPage (this);  // Set by `context` property

    console.log (`Processed index ${tIdx} (${tPage}). Its title was: "${pageTitle}"`);
}

function finishUpRequest (jqXHR, txtStatus) {
    var nextIdx     = this.arryIdx + 1;
    if (nextIdx < numPages) {
        var tPage   = listO_pages[nextIdx];
        //-- The setTimeout is seldom needed, but added here per OP's request.
        setTimeout ( function () {
            console.log (`Fetching index ${nextIdx} (${tPage})...`);
            getPageN (nextIdx);
        }, 222);
    }
}

function logError (jqXHR, txtStatus, txtError) {
    var [tIdx, tPage]   = getIdxAndPage (this);  // Set by `context` property
    console.error (`Oopsie at index ${tIdx} (${tPage})!`, txtStatus, txtError, jqXHR);
}

function getIdxAndPage (contextThis) {
    return [contextThis.arryIdx, listO_pages[contextThis.arryIdx] ];
}


这通常输出:

Processed index 0 (q/48/). Its title was: "Multiple submit buttons in an HTML form - Stack Overflow"
Fetching index 1 (q/27/)...
Processed index 1 (q/27/). Its title was: "datetime - Calculate relative time in C# - Stack Overflow"
Fetching index 2 (q/34/)...
Processed index 2 (q/34/). Its title was: "flex - Unloading a ByteArray in Actionscript 3 - Stack Overflow"
Fetching index 3 (q/69/)...
Processed index 3 (q/69/). Its title was: ".net - How do I calculate someone's age in C#? - Stack Overflow"
Fetching index 4 (badpage)...
GET https://whosebug.com/badpage?_=1512087299126 404 ()
Oopsie at index 4 (badpage)! error  Object {...

-- 取决于您的 Stack Overflow 声誉。


重要提示:不要尝试使用 async: false 技巧。这些只会:锁定您的浏览器,偶尔使您的计算机崩溃,并使调试和部分结果变得更加困难。