I have a simple if else scenario where I need to do something if a variable is set otherwise just perform in the else part:
if(flag) {
doSomething();
}
doNextThing(someParam);
If flag is set, then I must doSomething() and doNextThing()
Both doSomething and doNextThing return promises. What is the best way to implement this?
Currently my code looks like:
if(flag) {
doSomething().then(doNextThing);
}
else doNextThing(someParam);
What is the best way to elegantly combine the two in cleaner code segment?
I tried:
var somePromise = new Promise(function(resolve, reject){
if(flag)
doSomething.then(resolve(result));
else resolve();
})
return somePromise.then(doNextThing(resolvedValue))
but this doesn't work. Seems like the promise doSomething is never resolve and the code returns immediately. I also tried several variations of the above including:
var somePromise = new Promise(function(resolve, reject){
if(flag)
doSomething.then(resolve);
else resolve();
})
and:
var somePromise = new Promise(function(resolve, reject){
if(flag)
doSomething.then(function(result){
resolve(result);
}.bind(this));
else resolve();
}.bind(this));
but nothing works, except for the very first option. So, my question is - Is there a better/elegant way to achieve this?
Try moving to
Ember.RSVP.Promiseand returning promise in your function (it should chain them):