-1

I'm fully aware that async: false is deprecated with XMLHttpRequest, but the following code meets my immediate need to GET all pages before a subsequent task iterates over them.

for (i=0; i <= last_page; i++) {
      $.ajax({
          url : '/static/experiments/zoning_out_task/text/' + i + '.html',
          cache: false,
          async: false,
          success : function(result) {
              pages.push(result);
          }
      });
}

Is there a pattern that achieves the same thing using async: true?

Paul
  • 527
  • 5
  • 17
  • So you use promises and call after all the requests are complete http://api.jquery.com/jQuery.when/ – epascarello May 11 '17 at 13:02
  • You have to use [promise](https://api.jquery.com/promise/) to achieve such behaviour. – Mayank May 11 '17 at 13:02
  • Even You can change your code to reduce the number of ajax calls, try sending all the parameters at once instead of looping in the data and sending ajax calls. – Mayank May 11 '17 at 13:06
  • You can refer to [this post](http://stackoverflow.com/questions/5627284/pass-in-an-array-of-deferreds-to-when) as well – Mayank May 11 '17 at 13:07

1 Answers1

0

in es6 you can use promisy.all if you need them all before continue to the next task

var p1 = Promise.resolve(3);
var p2 = 1337;
var p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
}); 

Promise.all([p1, p2, p3]).then(values => { 
  console.log(values); // [3, 1337, "foo"] 
});

if you need to finish each task serially you can use async.waterfall

async.waterfall([
    function(callback) {
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback) {
        // arg1 now equals 'one' and arg2 now equals 'two'
        callback(null, 'three');
    },
    function(arg1, callback) {
        // arg1 now equals 'three'
        callback(null, 'done');
    }
], function (err, result) {
    // result now equals 'done'
});

you also can achieve this by promises

var p1 = new Promise( (resolve, reject) => {
  resolve('Success!');
  // or
  // reject ("Error!");
} );
    var p2 = new Promise( (resolve, reject) => {
  setTimeout(resolve, 1000, 'foo');
  // or
  // reject ("Error!");
} );
p1.then( value => {
  console.log(value); // Success!
    // here you can call the second promise and so on 
    p2.then(value=>{
       console.log("second promise done",value)
    })
}, reason => {
  console.log(reason); // Error!
} );
Fadi Abo Msalam
  • 6,739
  • 2
  • 20
  • 25