Take the below code for example. Is there anything wrong with mixing await with .then in scenarios like this? In my opinion it seems pointless and clunky to declare await for each step like const json = await assetParam.json()
etc.. when all we really care about is the final response (in this example at least). But someone told me that mixing await
with .then
can lead to some hard to diagnose bugs and I'm struggling to understand them.
Any information/resources would be greatly appreciated.
async function getParams(assetId) {
const reqUrl = `https://somelink/${assetId}`
const assetParam = await fetch(reqUrl)
.then((res) => res.json())
.then((json) => json.asset.params)
return assetParam
}
async
functions andawait
is to get around having to build.then()
callback chains. – Skellasync
/await
and.then
are totally interoperable. IMO it's better to stick to one or the other, at least on a per-module basis, though. And note that in your caseassetParam
isn't needed, you could just return the chain directly (at which point you don'tawait
anything and don't actually need to makegetParams
async
). – Guidonconst getParams = async url => (await ((await fetch(url)).json())).asset.params
– Carib