Search code examples
javascriptecmascript-6promisefetches6-promise

Using Promises In A For Loop.. How Do You Tell When It's Finished?


Here is the jsfiddle: https://jsfiddle.net/8ocdupar/

var arr = [0,1,2,3,4,5];

for (var i = 0; i < arr.length; i++) {
    fetch("https://jsonplaceholder.typicode.com/todos/1")
    .then(response => {
        console.log(response);
    });
}
console.log("DONE!!!")

In this straightforward example, I have a fetch promise inside a for loop. Based on the length of the array it will make the fetch call 6 times. My question is, how can I tell when it's done?

I don't understand async behavior very well. To me, it seems I want this example to actually behave synchronously.

When that loop is done and has made all the calls, I just want to log that it's done.

This is what the example currently outputs:

DONE!!!
(index):39 Response {type: "cors", url: "https://jsonplaceholder.typicode.com/todos/1", redirected: false, 
status: 200, ok: true, …}
(index):39 Response {type: "cors", url: "https://jsonplaceholder.typicode.com/todos/1", redirected: false, 
status: 200, ok: true, …}
(index):39 Response {type: "cors", url: "https://jsonplaceholder.typicode.com/todos/1", redirected: false, 
status: 200, ok: true, …}
(index):39 Response {type: "cors", url: "https://jsonplaceholder.typicode.com/todos/1", redirected: false, 
status: 200, ok: true, …}
(index):39 Response {type: "cors", url: "https://jsonplaceholder.typicode.com/todos/1", redirected: false, 
status: 200, ok: true, …}
(index):39 Response {type: "cors", url: "https://jsonplaceholder.typicode.com/todos/1", redirected: false, 
status: 200, ok: true, …}

And this is what I want it to output:

(index):39 Response {type: "cors", url: "https://jsonplaceholder.typicode.com/todos/1", redirected: false, 
status: 200, ok: true, …}
(index):39 Response {type: "cors", url: "https://jsonplaceholder.typicode.com/todos/1", redirected: false, 
status: 200, ok: true, …}
(index):39 Response {type: "cors", url: "https://jsonplaceholder.typicode.com/todos/1", redirected: false, 
status: 200, ok: true, …}
(index):39 Response {type: "cors", url: "https://jsonplaceholder.typicode.com/todos/1", redirected: false, 
status: 200, ok: true, …}
(index):39 Response {type: "cors", url: "https://jsonplaceholder.typicode.com/todos/1", redirected: false, 
status: 200, ok: true, …}
(index):39 Response {type: "cors", url: "https://jsonplaceholder.typicode.com/todos/1", redirected: false, 
status: 200, ok: true, …}
DONE!!!

Solution

  • Use async and await:

    (async function () {
      var arr = [0,1,2,3,4,5];
      for (var i = 0; i < arr.length; i++) {
        let response = await fetch("https://jsonplaceholder.typicode.com/todos/1")
        let o = await response.json(); // <-- you'll want this too...
        console.log(o);
      }
      console.log("DONE!!!")
    })(); // <-- execute it