Julien S
Julien S

Reputation: 91

Using Promise.all to execute a function after other ones

I'm trying to execute my function HideEmptyTile once all the previous functions are finished.

I was using TimeOut until now but this is not really a proper way to do what I want to accomplish.

Here is my previous code :

        retrieveAccountOpenWithVisitObjectif(userId, processOpenWithVisitObjectif);
        retrieveAccountOpen(userId, processAccountOpen);
        retrieveAllActivitiesOpen(userId, processAllActivitiesOpen);
        setTimeout("HideEmptyTile()", 800); 

After few researches I found that I could use an other callback function, but it seems that Promise.all as been build for my case. So I did the next code :

Promise.all(
        retrieveAccountOpenWithVisitObjectif(userId, processOpenWithVisitObjectif),
        retrieveAccountOpen(userId, processAccountOpen),
        retrieveAllActivitiesOpen(userId, processAllActivitiesOpen)).then(HideEmptyTile()); 

The issue is that this is not the behaviour that I would like to have since the function HideEmptyTile is not executed after the other functions.

Am I using Promise.all in the wrong way?

Upvotes: 1

Views: 297

Answers (3)

Batman25663
Batman25663

Reputation: 272

  1. Promise.all takes an array to fulfill the promises.
  2. You are passing the HideEmptyTile()in the then block. You need to pass inside the callBack:

Promise.all([
        retrieveAccountOpenWithVisitObjectif(userId, processOpenWithVisitObjectif),
        retrieveAccountOpen(userId, processAccountOpen),
        retrieveAllActivitiesOpen(userId, processAllActivitiesOpen)]).then(function(){
          HideEmptyTile();
        }); 

Upvotes: 0

Faly
Faly

Reputation: 13346

Ensure all your functions returns promise, then you will achieve your goal by:

var promises = [
    retrieveAccountOpenWithVisitObjectif(userId, processOpenWithVisitObjectif),
    retrieveAccountOpen(userId, processAccountOpen),
    retrieveAllActivitiesOpen(userId, processAllActivitiesOpen)
];

Promise.all(promises).then(() => HideEmptyTitle());

Upvotes: 1

Bergi
Bergi

Reputation: 664375

  • Promise.all takes an array of promises, not multiple arguments
  • then takes a function (you were already calling it and passing the result)

Promise.all([
    retrieveAccountOpenWithVisitObjectif(userId, processOpenWithVisitObjectif),
    retrieveAccountOpen(userId, processAccountOpen),
    retrieveAllActivitiesOpen(userId, processAllActivitiesOpen)
]).then(HideEmptyTile);

Upvotes: 5

Related Questions