Search code examples
javascriptpromise

Javascript Promise.all call a function with .then()


I use Promise.all the trig a function after all promise are resolved.

It works but I don'd understand why to call a function I havo to use an anonimus funtion and I can't call the my function directly. This is the example.

Promise.all(jarOfPromise)
  .then(_ => {
    drawAllCard(images);
  });
  //.then(drawAllCard(images));

if I call the function directly like this:

Promise.all(jarOfPromise)
  .then(drawAllCard(images));

it don't works, with any error.

I try to looking for a reason for that but I don't find any explination.


Solution

  • When you do it like this:

    Promise.all(jarOfPromise)
      .then(drawAllCard(images));
    

    You are calling drawAllCard(images) immediately. That not passing a callback that can be called later. You're passing the result of an expression. So, for Javascript to get that result, it has to evaluate the expression which means executing drawAllCard(images) before Promise.all().then() is even executed. The return result from executing drawAllCard(images) which I will call temp is then passed to .then() as in:

     Promise.all(jarOfPromise).then(temp)
    

    This ends up equivalent to this:

    const temp = drawAllCard(images);
    Promise.all(jarOfPromise).then(temp);
    

    But, when you do it like your first example, you are passing a callback function to .then(). That allows .then() to call that callback LATER when the promise resolves. Passing drawAllCard(images) is not a callback function, that's an expression that will get executed to get the return result and it's the return result that will get passed to .then().

    But, doing it like this:

    Promise.all(jarOfPromise).then(_ => {
        drawAllCard(images);
    });
    

    Is passing a callback to .then() that can be called later.