It is often said that async
/ await
and then()
should not be mixed.
However, consider a scenario where we want a utility function that fetches user data, which we want to await
upon consumption elsewhere in the code base:
const getUser = async () => {
const userPromise = fetch(...)
.then((res) => res.json())
.then((user) => JSON.stringify(user));
return userPromise;
};
Unless I have misunderstood, the above allows us to convert the return value of the fetch promise into a promise that returns the final user data in json format, when await'ed later:
const user = await getUser();
My idea was that nesting then()
here ensures we do not have to write lines to unpack the json, when consuming getUser
later.
Is that a valid use case for mixing then and async/await, or is it an antipattern?