Reputation: 2290
I am trying to reduce the need for multiple functions, especially as many have a promise
that is doing the same thing. However, I am looking to add a condition based on props
from a parent.
For example I have a function
example
.doSomething()
.then(something => {
example.createSomething(something)
});
But how can I add a condition that changes .doSomething()
from props
of somethingElse
to .doSomethingElse()
?
Therefore, if somethingElse === true
the function will be
example
.doSomethingElse()
.then(something => {
example.createSomething(something)
});
Upvotes: 1
Views: 623
Reputation: 102
You can use Promise.all method
let cleaRoom = function(){
return new Promise(function(resolve, reject){
resolve('room is cleaed')
})
}
let removeGarbage = function(message){
return new Promise(function(resolve, reject){
resolve(message + ' garbage is removed')
})
}
let wonIcecream = function(message){
return new Promise(function(resolve, reject){
resolve(message + ' won the icecream');
})
}
Promise.all([cleaRoom(),removeGarbage(),wonIcecream()]).then(function(){
console.log('finished all');
})
Upvotes: 0
Reputation: 1763
I am writing this in my phone don't blame me, might tidy up later.
Promise.resolve(somethingElse ? example.doSomethingElse() : example.doSomething())
.then(...
if you think writing twice example
is tedious
Promise.resolve(example[somethingElse ? "doSomethingElse" : "doSomething"]())
.then(...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
By @Phil
if both(all) functions return a Promise
can simply do
example[somethingElse ? "doSomethingElse" : "doSomething"]().then(...
Note that it means Promise.resolve
above can even handle non-Promise return value
Upvotes: 2