I would like to write a function getUser()
that returns a Promise where upon resolve
it delivers the user object and upon reject
it delivers the error. I'm using axios to make the request.
Here's what I currently have.
async function getUser() {
try {
const userResponse = await axios({
method: 'post',
url: "some_url",
data: "some string data",
headers: {
'content-type': 'application/x-www-form-urlencoded'
}
});
if (userResponse.data.status === 'success') {
// resolve(validateResponse.data);
} else {
// reject(validateResponse.data);
}
} catch (error) {
// reject(validateResponse.data);
}
}
I would like to wrap the entire try...catch
block inside a Promise
constructor, but the Promise constructor is new Promise((resolve, reject) => {...})
and not new Promise(async (resolve, reject) => {...})
. I know I can do the latter but it's an anti-pattern.
The Promise
approach doesn't necessarily work either because when I use the Promise
returned by getUser()
and .catch()
any errors, I won't know if the error came from the response from the server (the status was not 'success'
) or if the request itself failed.
What is the safest way to get around this problem? I know there is a brute force solution of just mimicking the Promise
API without actually using it, or declaring an async
Promise, but I feel like I'm encountering an anti-pattern every time.
Thanks for any suggestions.