Skip to content
Advertisement

Using Promise in a for loop, all the .then came later is always be called untill all the first .then is finished running, why is that?

I am new to JavaScript and with the concept of Promise. And I am doing test.

I created a promise and two for loop that runs Promise for 6 times in total, and I knows when they got executed by console.log()

Here’s my code

JavaScript

and here’s how the console be like:

JavaScript

Why is the second .then and all the .finally will wait for every single first .then and then being execute?

I know I probably missing some basic concepts in Javascript in my knowledge database stored inside my brain :), please let me know what concept in JS will be regarding this issue, I would take a look, Thanks!

Advertisement

Answer

If you notice, in your example, you referenced/assigned a promise to a variable (let p = new Promise((resolve, reject)=> {....), and then you used the variable p, which now has the reference of the same instance of promise, in your for loops.

Keep in mind that a reference of a promise, once it’s fulfilled, will always return the same result. For example:

JavaScript

That’s probably why you saw what your saw in the console.log(). Basically the two for loops executed the same reference of the promise asynchronously, in which each sequence of handlers (.then and .finally) completes at the same time (or almost).

To properly demonstrate what you want to achieve, you will need to execute a new instance of a Promise on every iteration. Another example:

JavaScript

You should then see this log with something like:

JavaScript

Let me know if this clears things up for you. Good luck!

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement