简体   繁体   中英

React async function not returning correctly

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

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; 

working solution: change the for of loop to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM