jengfad
jengfad

Reputation: 734

Make sure promise is executed after a conditional promise

I have an if-else condition with different promises inside. After the logic has picked which condition it will enter and had executed the promise, I have to make sure that my final promise is executed.

if (a < 5)
{
   vm.promise1()
   .then((data) => {
      //do something with data
   })
}
else if (a > 5)
{
	vm.promise2()
   .then((data) => {
      //do something with data
   })
}
else
{
	vm.promise3()
   .then((data) => {
      //do something with data
   })
}

Now I have vm.finalPromise() to be executed after the condition. I don't want to put .finally() on every single promise in each of the condition. Is there any other implementation?

Thanks

Upvotes: 0

Views: 56

Answers (2)

EyuelDK
EyuelDK

Reputation: 3199

In my opinion, I would suggest you keep it "Promisy" Instead of storing a promise into a variable, call a function that returns some promise. Note, this is just a style preference.

function doSomething() {
  if (a < 5) {
    return vm.promise1().then((data) => {
      //do something with data
    });
  } else if (a > 5) {
    return vm.promise2().then((data) => {
      //do something with data
    });
  } else {
    return vm.promise3().then((data) => {
      //do something with data
    });
  } 
}

doSomething().then(() => {
  // finally do something
});

Upvotes: 2

Jaromanda X
Jaromanda X

Reputation: 1

Create a var to hold any of those promises

Use it like any other promise after the if/else if etc code

var p;
if (a < 5) {
   p = vm.promise1()
   .then((data) => {
      //do something with data
   })
} else if (a > 5) {
    p = vm.promise2()
   .then((data) => {
      //do something with data
   })
} else {
    p = vm.promise3()
   .then((data) => {
      //do something with data
   })
}
p.then((result) => {
     // do your magic here
});

Upvotes: 1

Related Questions