When working with Promises in javascript, it's important to be aware of anti-patterns that can arise. Let's consider a scenario where we have a request function that returns a Promise and we want to handle the response inside another function, executing specific code in the 'then' block, and then resolving or rejecting based on certain conditions:
export const login = (req: IRegisterAuthReq): Promise<IUserTokenResponse> => {
return new Promise((resolve, reject) => {
AuthApi.login(req)
.then(response => {
if (response.success) {
store.dispatch(setUserLoggedIn(true));
resolve(response.data as IUserTokenResponse);
} else {
reject();
}
})
.catch(reject)
.finally(() => {
store.dispatch(setAppLoading(false));
});
});
};
In this code snippet, we're calling the AuthApi.login function, handling the response, and then resolving the value.
You can then use this code like so:
login(req)
.then(authoredSuccessful)
.catch(authoredUnsuccessful);
If you're unsure whether this approach is considered an anti-pattern or not, or if there might be a better way to achieve similar functionality, feel free to ask for advice on alternative methods.