I am novice in JavaScript/TypeScript Promise return type.
The problem is I am hosting a rest API endpoint which internally invokes another API from a different service that returns a Promise object using JS Request module.
I want to unwrap the internal API promise response and create a new normal Typescript object and finally return the new modified response object rather than a Promise.
Here is a sample code to describe my problem:
export class SampleClass {
public process(): NewResponse {
const newResponse: NewResponse = new NewResponse();
// invokeOtherAPI() call Returns a Promise by invoking a different endpoint
invokeOtherAPI().then(function (result) {
newResponse.propertyOne = result.propertyOne;
newResponse.propertyTwo = result.propertyTwo;
});
return newResponse;
}}
In this case the process() returns an empty value though it gets assigned inside the then().
Here is my controller class for the REST API (Path decorators are missing)
export class SampleController() {
const service: SampleClass = new SampleClass();
public get(): NewResponse {
return service.process();
}
}
Questions:
- Is it a good practice to return the Promise object all the time from a Typescript API?
- Is there a way I can unwrap a promise object internally and return a non promise object from an API?
Thanks for any help on this.