How to set callback order invocation same as target function invocation

后端 未结 3 2056
谎友^
谎友^ 2021-01-29 10:33

I have a problem in my project.

To describe this issue I have wrote simplified code snippet:

function waitFor(fnReady, fnCallback) {
    var check = fun         


        
3条回答
  •  无人共我
    2021-01-29 10:50

    Try this pattern

    var map = "abcdefghi".split("");
    var responses = []; // collect responses
    $.ajaxSetup({
        beforeSend : function(jqxhr, settings) {
          jqxhr.id = Number(settings.data.split(/id=/)[1]); // add `id` to `request`
            console.log(settings.data.split(/id=/)[1]);
        }
    });
    var request = function(id, data) {
        // append `id` to `id` data
        return $.post("/echo/json/", {json:JSON.stringify([data]), id:id})
    };
    
    $.each(map, function(k, v) {
        setTimeout(function() {
          request(k + 1, v)
          .done(function(data) {
            // do stuff at each response
            console.log(data); // note return values
          })
          .always(function(data, textStatus, jqxhr) {
              // do stuff at each response
              responses.push([jqxhr.id, data[0]]);
              // do stuff when all requests completed , results items in `responses`
              if (responses.length === map.length) {
                  responses.sort(); // sort `responses` based on `id`
                  // do stuff with `responses`
                  console.log(responses);
              }
          });
        },1 + Math.random() * 1000) // async
    });
    

    jsfiddle http://jsfiddle.net/guest271314/g254bbjg/

提交回复
热议问题