React async function not returning correctly

138 Views Asked by At

I'm calling a util function in a component like this:

const res = await makeTempTrackImports({artistName,QueryID});

The util function calls some data from supabase, does some string methods then does an async for of loop where I call the Spotify API with the data. after this point, the data isn't consistently returning in the util function or if I try to return back to the component. Here's what the util looks like

export const makeTempTrackImports = async ({ artistName, QueryID }) => {
    const { data } = await 
    supabase.storage.from("audio").list(QueryID);
    const trackNames = Object.values(data).map((song) => {
        return song.name.replace(/_/g, "&").replace(".mp3", "");
    });

    let results = [];
    for await (const songName of trackNames) {
        const res = await getTrackIds({songName, artistName});
        if (res === 0 || res === undefined) return;
        results.push(res.tracks.items);
    }
    return results; <-- stops working by here
}; 

the result will show up in the console inconsistently but won't actually be returned in the program. thank you in advance

2

There are 2 best solutions below

0
Michael Brenndoerfer On

You are returning too early. the return will return from the function scope, not returning the empty [] results array. Slight change of your if condition should do the trick.

for await (const songName of trackNames) {
    const res = await getTrackIds({
        songName,
        artistName
    });
    if (res) results.push(res.tracks.items);
    // or if (res === 0 || res === undefined) return results;
    
}
return results; 
0
datamosh On

working solution: change the for of loop to

const results = await Promise.all(
  trackNames.map(
    (songName) => getTrackIds({songName, artistName})
  )
);