0

Below test() function will be called 6 times inside a loop by loopTheTest().

I want these 6 calls to be run synchronously.

I know async:false is a bad practice, and I couldn't find a clear solution on how to achieve this.

I checked topics promises and async-await, but couldn't apply them to below case (due to my lack of knowledge).

P.S: I'am not looking for a recursive solution.

function loopTheTest(){

     var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];

     for (i = 0; i < cars.length; i++) {
         test(cars[i]);
     }
}
function test(car){
    //Some Codes
    //AJAX POST REQUEST
    //Some Codes
}
2
  • 1
    A better way would be to handle arrays on server side to have to call it only once with all values. Else you can always make your requests synchronous by passing false as third parameter. developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/… Commented Dec 6, 2019 at 14:30
  • Promise.all(cars.map(test)).then(function(arrayOfResults) { /* do something with the results */ }); Commented Dec 6, 2019 at 18:53

3 Answers 3

1

With async/await and using jsonplaceholder to have a 'real' fetch(), you can get your result with a for/of loop :

require('isomorphic-fetch');

const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
const url = "https://jsonplaceholder.typicode.com/albums/";

async function test(car,i){
    const result = await fetch(url+(i+1));
    const descr = await result.json();
    return cars[i] + " " + descr.title;
}

async function loopTheTest() {
    for (const [i, car] of cars.entries()) {
      let res = await test(car,i);
      console.log(`Received test ${i + 1}:`, res);
    }
    console.log(' Finish !!!');
  }

loopTheTest();

You get :

Received test 1: BMW quidem molestiae enim
Received test 2: Volvo sunt qui excepturi placeat culpa
Received test 3: Saab omnis laborum odio
Received test 4: Ford non esse culpa molestiae omnis sed optio
Received test 5: Fiat eaque aut omnis a
Received test 6: Audi natus impedit quibusdam illo est
 Finish !
Sign up to request clarification or add additional context in comments.

4 Comments

What is isomorphic-fetch? . And can you implement above code on jsfiddle ? I couldn't make it work.
it's just in case you are executing that in nodeJS (server side).
otherwise replace jsonplaceholder with your server url to avoid CORS issues
I tried to implement your code but I guess I am missing something. Can you check my other thread with my real codes ? stackoverflow.com/questions/59219048/…
0

When you loop with Ajax, call the next Ajax in the success:

var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
cnt = 0;

function test() {
  if (cnt >= cars.length) return; // stop

  var car = cars[cnt];
  fetch("someprocess?car=" + car)
    .then(function(data) {
      showFunction(data);
      cnt++;
      test();
    })
}
test()

2 Comments

thanks, but in my case, I am not looking for a recursive solution. I need a solution including a for loop. I simplified my code before posting to stackoverflow.
I wish I was that young. :)
0

If you want them to run sequentially, something like this should work

var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
async function test() {
    for (let index = 0; index < cars.length; index++) {
        const data = await fetch("someprocess?car=" + cars[index])
        // do whatever you want to do with the response data here
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.