Reputation: 82
I have a function calc(), which may have following:
calc() {
...
if (condition) {
return new Promise(...) ; // promise1
}
else {
return new Promise(...); // promise2
}
}
The function calls it will act on these two promises differently:
calc().then()=>{ do something; } // if promise 1;
.then()=>{ do nothing; } // if promise 2;
Is it possible to do?
The reason I am asking is that calc() itself is an asynchronous function. It is subscribing to some process like:
calc () {
subscribe(()=> { do something and need to flash upper caller that is done;}
}
so if calc() does not receive signal from another process, it will not yield results, and upper caller does have the necessary data to proceed.
Upvotes: 1
Views: 91
Reputation: 92
Assuming you know the result of the condition synchronously. Why not wrap the promises in an object and have a property such as id, to denote which promise was returned?
calc() {
...
if (condition) {
return { id: 1, promise: new Promise(...) }; // promise1
}
else {
return { id: 2, promise: new Promise(...) }; // promise2
}
}
You can then decide what to do with the promises based on the id returned.
const result = calc();
if(result.id === 1){
result.then()=>{ do something; } // if promise 1;
}
else if(result.id === 2) {
result.then()=>{ do nothing; } // if promise 2;
}
Upvotes: 1