In software development, there is a classic technique where a method returns the result of another method call:
method1(): ObjectX {
if( condition1 )
return method2();
return undefined // or some default value;
}
method2(): ObjectX {
let res: ObjectX;
// some IO operations
return res;
}
However, I am now interested in utilizing Promise<ObjectX>
as the return type of method2 (due to potential IO operations).
This modification transforms method2 into:
method2() : Promise<ObjectX> {
return new Promise((resolve)=> {
let res: ObjectX;
// some IO operations
resolve(res);
})
}
The challenge lies in method1.
Why CAN'T IT BE structured like this:
method1() : Promise<ObjectX> {
if( condition1)
return this.method2();
return new Promise((reject)=> { reject('error'); })
}
Why must a method that needs to return a promise NOT be able to return the result of another method (which also returns a Promise)?
Why is it necessary for the method to "unpack" the received promise, extract the result, and then resolve its own Promise with this result?
For example, why do we have to structure it like this:
method1() : Promise<ObjectX> {
return new Promise((resolve, reject) => {
if( condition1)
method2().then( (r) => resolve(r) ); // extracting result from received promise and resolving my own
reject('error');
});
I mean, this approach works, but I am curious about why the previous method1 implementation doesn't suffice.
More broadly, imagine a chain of methods calling each other and passing an object along. If I introduce a Promise in the final method's return type, I find myself needing to extensively modify all methods in the sequence - not just their signatures and return statements.
Is there an alternative technique to achieve this without such significant code modifications?