Javascript 如何按顺序(等待上一次)循环执行GET/POST调用?

Javascript 如何按顺序(等待上一次)循环执行GET/POST调用?,javascript,jquery,userscripts,tampermonkey,Javascript,Jquery,Userscripts,Tampermonkey,我正在为一个网页编写一个脚本,并试图从其他网页中提取数据。 我正在尝试创建一个函数,该函数内部有一个循环,该循环遍历一个列表,llcList,并从ajax方法GET检索数据,但希望在转到第二个请求之前等待完成一个请求。 如果我能让它多等一段时间的话,我会得到额外的奖励 应该发生什么: 发送llcList[0]的请求 获取返回数据,并对其进行处理 等一会儿 发送新的llcList请求[1] 这可能吗?我尝试了几种方法,每次循环发送所有请求时,间隔不到一秒钟 function F_Company_L

我正在为一个网页编写一个脚本,并试图从其他网页中提取数据。
我正在尝试创建一个函数,该函数内部有一个循环,该循环遍历一个列表,
llcList
,并从ajax方法GET检索数据,但希望在转到第二个请求之前等待完成一个请求。
如果我能让它多等一段时间的话,我会得到额外的奖励

应该发生什么:

  • 发送llcList[0]的请求
  • 获取返回数据,并对其进行处理
  • 等一会儿
  • 发送新的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);}
    
    功能F_Company_LLC(){
    对于(i=0;i
    使用异步ajax请求模拟for循环。在ajax的
    完全回调中
    转到列表中的下一项:

    function F_Company_LLC(llcList) {
        var i= 0;
    
        function getNext() {
    
               if(llcList[i][2]=="lab"){
                    //run function 0
    
                        ++i;
    
                        getNext();
                }
                else if(llcList[i][2]=="shop"){
                    //run function 1
    
                        ++i;
    
                        getNext();
                }
                else{
    
                 $.ajax({
    
                  url: base_link+"/company/edit_company/"+llcList[i][1], //CompID
                  method: 'GET',
                  async: true,
                  success: function(data) {
                    if (data.status == "success" && i <= llcList.length) {
                         //data processing
                     }
                   },
                   error: function(xhr) { 
                    alert("Error while processing CompID: " + llcList[i][1]);
    
                   },
                  complete: function() {
                 //complete executes after either 
                 //the success or error callback were executed.
                         ++i;
                        getNext();//go to next item in the list
                  },
                 });      
                }  
        }
    
        getNext();
    }
    
    
    F_Company_LLC(llcList);
    
    功能F_Company_LLC(llcList){
    var i=0;
    函数getNext(){
    如果(llcList[i][2]=“实验室”){
    //运行函数0
    ++一,;
    getNext();
    }
    else if(llcList[i][2]=“店铺”){
    //运行函数1
    ++一,;
    getNext();
    }
    否则{
    $.ajax({
    url:base_link+“/company/edit_company/”+llcList[i][1],//CompID
    方法:“GET”,
    async:true,
    成功:功能(数据){
    
    if(data.status==“success”&&i使用异步ajax请求模拟for循环。在ajax的
    完成回调上转到列表中的下一项:

    function F_Company_LLC(llcList) {
        var i= 0;
    
        function getNext() {
    
               if(llcList[i][2]=="lab"){
                    //run function 0
    
                        ++i;
    
                        getNext();
                }
                else if(llcList[i][2]=="shop"){
                    //run function 1
    
                        ++i;
    
                        getNext();
                }
                else{
    
                 $.ajax({
    
                  url: base_link+"/company/edit_company/"+llcList[i][1], //CompID
                  method: 'GET',
                  async: true,
                  success: function(data) {
                    if (data.status == "success" && i <= llcList.length) {
                         //data processing
                     }
                   },
                   error: function(xhr) { 
                    alert("Error while processing CompID: " + llcList[i][1]);
    
                   },
                  complete: function() {
                 //complete executes after either 
                 //the success or error callback were executed.
                         ++i;
                        getNext();//go to next item in the list
                  },
                 });      
                }  
        }
    
        getNext();
    }
    
    
    F_Company_LLC(llcList);
    
    功能F_Company_LLC(llcList){
    var i=0;
    函数getNext(){
    如果(llcList[i][2]=“实验室”){
    //运行函数0
    ++一,;
    getNext();
    }
    else if(llcList[i][2]=“店铺”){
    //运行函数1
    ++一,;
    getNext();
    }
    否则{
    $.ajax({
    url:base_link+“/company/edit_company/”+llcList[i][1],//CompID
    方法:“GET”,
    async:true,
    成功:功能(数据){
    
    if(data.status==“success”&&i这是一个常见的场景。请注意,通常不需要按顺序处理调用。通常只需发送ajax调用的上下文,并在半随机出现时将所有内容拼凑在一起就足够了,如中所示


    强制执行顺序行为的一种方法是通过
    complete
    函数链接调用。以下是演示该过程的全功能代码。要使用,请在堆栈溢出页面上将其粘贴到浏览器控制台中:

    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://stackoverflow.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] ];
    }
    
    var listO_pages=[“q/48/”、“q/27/”、“q/34/”、“q/69/”、“badpage”];
    var numPages=listO_pages.length;
    getPageN(0);//--启动链式回迁
    函数getPageN(K){
    如果(K>=0&&K

    这通常会输出:

    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://stackoverflow.com/badpage?_=1512087299126 404 () Oopsie at index 4 (badpage)! error Object {... 已处理索引0(q/48/)。其标题为:“HTML表单中的多个提交按钮-堆栈溢出” 正在获取索引1(q/27/)。。。 处理索引1(q/27/)。它的标题是:“datetime-计算C#-堆栈溢出中的相对时间” 正在获取索引2(q/34/)。。。 处理索引2(q/34/)。它的标题是:“flex-在Actionscript 3中卸载ByteArray-堆栈溢出” 正在获取索引3(q/69/)。。。 处理索引3(q/69/)。它的标题是:“.net-我如何用C#计算某人的年龄?”叠加