How to make all AJAX calls sequential?

2019-01-06 15:17发布

I use jQuery. And I don't want parallel AJAX calls on my application, each call must wait the previous before starting. How to implement it? There is any helper?

UPDATE If there is any synchronous version of the XMLHttpRequest or jQuery.post I would like to know. But sequential != synchronous, and I would like an asynchronous and sequential solution.

11条回答
Bombasti
2楼-- · 2019-01-06 16:10

Set the async option to false, e.g.,

$.ajax({ async: false /*, your_other_ajax_options_here */ });

Reference: Ajax/jQuery.ajax

查看更多
别忘想泡老子
3楼-- · 2019-01-06 16:11
(async () => { 
  for(f of ['1.json','2.json','3.json']){
    var json = await $.getJSON(f);
    console.log(json)
 };
})()
  1. requests 3 json files with jQuery ajax calls
  2. process in sequence (not in parallel) with await
  3. works in Chrome/Firefox/Edge (as of 1/30/2018)

more at MDN

查看更多
爷的心禁止访问
4楼-- · 2019-01-06 16:17

You could give narrative javascript a try http://www.neilmix.com/narrativejs/doc/

I've never used it myself though. If I wanted to do this, I would setup some kind of abstraction for chaining asynchronous actions. As others have said, the synchonous version of the ajax object blocks events from being processed while it's waiting for a response. This causes the browser to look like it's frozen until it recieves a response.

查看更多
Deceive 欺骗
5楼-- · 2019-01-06 16:17

sequential != synchronous, and I would like an asynchronous and sequential solution

Synchronous execution generally means "using the same clock", while sequential execution means "following in order or sequence".

For your specific use case I think both conditions must be met, as asynchronous execution implies the possibility of a non-sequential result.

查看更多
劫难
6楼-- · 2019-01-06 16:19

How about using Node.js events?

var EventEmitter = require('events').EventEmitter;
var eventEmitter = new EventEmitter();
var $ = require('jquery');

var doSomething = function (responseData) {
  var nextRequestData = {};
  // do something with responseData
  return nextRequestData;
};

// ajax requests
var request1 = $.ajax;
var request2 = $.ajax;
var requests = [request1, request2];

eventEmitter.on('next', function (i, requestData) {
  requests[i](requestData).then(
    function (responseData) {
      console.log(i, 'request completed');
      if (i+1 < requests.length) {
        var nextRequestData = doSomething(responseData);
        eventEmitter.emit('next', i+1, nextRequestData);
      }
      else {
        console.log('completed all requests');
      }
    },
    function () {
      console.log(i, 'request failed');
    }
  );
});

var data = {
  //data to send with request 1
};
eventEmitter.emit('next', 0, data);
查看更多
登录 后发表回答