How do I return a proper TypeScript Promise?
I’m learning Angular 2 with TypeScript and am working on creating a mocking service. This service should return a Promise if the object is saved successfully and return an error if anything goes wrong.
Here is the code I’ve tried, but TypeScript is throwing an error: “No best common type exists among return expressions”:
saveMyClass(updatedMyClass: MyClass) {
// saving MyClass using http service
// return the saved MyClass or error
var savedMyClass: MyClass = someLogicThatReturnsTheSavedObject(updatedMyClass);
if (isSomeCondition)
return Promise.reject(new Error('No reason but to reject'));
else
return new Promise<MyClass>(resolve => {
setTimeout(() => resolve(savedMyClass), 1500);
});
}
What should be the correct code to return a Promise in TypeScript so I can use it in my component to either consume the returned MyClass or reflect an error if one occurs in the service?
Hello,
Ensure that both the success and error paths return the same type: Promise<MyClass>
. You can do this by rejecting with a typed error.
saveMyClass(updatedMyClass: MyClass): Promise<MyClass> {
const savedMyClass: MyClass = someLogicThatReturnsTheSavedObject(updatedMyClass);
if (isSomeCondition) {
return Promise.reject<MyClass>(new Error('No reason but to reject'));
} else {
return new Promise<MyClass>((resolve) => {
setTimeout(() => resolve(savedMyClass), 1500);
});
}
}
Hope this will help you resolve your query.
This approach ensures that only one Promise is created, and the logic for success and error handling is wrapped inside it.
saveMyClass(updatedMyClass: MyClass): Promise<MyClass> {
return new Promise<MyClass>((resolve, reject) => {
const savedMyClass: MyClass = someLogicThatReturnsTheSavedObject(updatedMyClass);
setTimeout(() => {
if (isSomeCondition) {
reject(new Error('No reason but to reject'));
} else {
resolve(savedMyClass);
}
}, 1500);
});
}
Here, both the resolve and rejection are handled within the same Promise.
This solution is more idiomatic in modern TypeScript and Angular applications.
async saveMyClass(updatedMyClass: MyClass): Promise<MyClass> {
try {
const savedMyClass: MyClass = someLogicThatReturnsTheSavedObject(updatedMyClass);
if (isSomeCondition) {
throw new Error('No reason but to reject');
}
return new Promise<MyClass>((resolve) => {
setTimeout(() => resolve(savedMyClass), 1500);
});
} catch (error) {
return Promise.reject(error);
}
}
Using async/await improves code readability, especially when dealing with asynchronous operations.