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(){
        var url = 'http://localhost:3002/categorias'
        const response = await axios.get(url);
        var categorias =
        var catRandom = []
        var i = 5
            var j = Math.floor(Math.random() * categorias.length)
            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 =
            console.log(ret)  // returns data, fine
        console.log(ret)  // returns "[]", empty
        return ret


.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 = (element) => {
        const url = 'http://localhost:3002/textos/categoria/' + element;
        const response = await axios.get(url);
        const dado =
        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