Skip to content
Advertisement

await does not affect async function

Hi i’m fairly new to javascript and I’m having a problem with my async function inside the AddEventListener method that is not awaiting the fetch result, so when i try to console.log(track_info.tracks) it prints out undefined.

JavaScript

Advertisement

Answer

Solution

You need to add an await to the call of getTrack. var track_info = await getTrack(urlTrack);

Helpful Tips

How to await fetch You do not need to await both fetch and result.json as you are awaiting an already returned result. You can await result.json, however awaiting fetch in this instance is not needed since fetch is returning a promise.

How to await promises You created an asynchronous function, and just like fetch, you need to await the result before continuing. A good rule of thumb is that you should await an asynchronous function whenever you need to reference the data returned. You awaited fetch() so you could access result.json(). Likewise, you await getTrack() so you can console.log its return value.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement