简体   繁体   English

反应异步 function 未正确返回

[英]React async function not returning correctly

I'm calling a util function in a component like this:我在这样的组件中调用 util function:

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. util function 从 supabase 调用一些数据,执行一些字符串方法,然后执行异步 for of 循环,在其中我用数据调用 Spotify API。 after this point, the data isn't consistently returning in the util function or if I try to return back to the component.在这一点之后,数据并没有始终如一地返回到 util function 或者如果我尝试返回到组件。 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.返回将从 function scope 返回,不返回空的[]结果数组。 Slight change of your if condition should do the trick.稍微改变你的 if 条件应该可以解决问题。

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工作解决方案:将 for of 循环更改为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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