Not receiving data from outside of a async forEach

I was doing this function on a React Native app, when I tried to return some data that i got from axios.get, but outside of forEach, it is empty, while inside it, it has the data. How could I fix this?

async function search(){
    try{
        var url = 'http://localhost:3002/categorias'
        const response = await axios.get(url);
        var categorias = response.data
        var catRandom = []
        var i = 5
        while(i--){
            var j = Math.floor(Math.random() * categorias.length)
            catRandom.push(categorias[j]["id"])
            categorias.splice(j, 1)
        }
        var ret = []
        await catRandom.forEach(async (element) => {
            var url = 'http://localhost:3002/textos/categoria/' + element
            const response = await axios.get(url);
            var dado = response.data
            ret.push(dado)
            console.log(ret)  // returns data, fine
        });
        console.log(ret)  // returns "[]", empty
        return ret
    }
    catch(error){
        console.error(error)
    }
}

Answer

.forEach returns undefined so even if there is an await in front of it, it won’t await for all the async callbacks to be complete. The second log that prints an empty array happens before the ones inside the forEach callbacks.

If you don’t mind all requests happening in parallel, you could use .map instead.It will return an array of promises that will resolve with whatever gets returned inside the callback.

    const promArr = catRandom.map(async (element) => {
        const url = 'http://localhost:3002/textos/categoria/' + element;
        const response = await axios.get(url);
        const dado = response.data
        return dado;
    });
    const res = await Promise.all(promArr);
    return res;

I’ve used Promise.all to be able to wait for all the promises to be fulfilled. Promise.all docs