asynchronous foreach in javascript

Asked

Viewed 795 times

2

Good morning!

After breaking my head and not finding the solution, I came to ask Sopt’s friends. It is possible to create an asynchronous foreach?

'Cause the next thing, look at my code:

async function generateWishlist() {
    var products = [];
    var productLength = 0;

    JSON.parse(getCookieVal('whishlistLEL')).forEach(function(e) {
         fetch("/api/catalog_system/pub/products/search?fq=productId:" + e)
        .then(a => a.json())
        .then(a => {
            products.push(a[0]);
            console.log("Estou passando por aqui hahah, estou te trolando, Lucas")
            productLength++;
        });      
    });  
    return new Promise(function(resolve) {
        resolve([products, productLength]);
    });
}

async function initWishlist() {
    if(!verifyWishlist()) {
        console.log("Você não possui produtos na lista de desejos!");
        return false;
    }
    await generateWishlist()
    .then(function(resolve) {
        console.log(resolve);
    })
}

initWishlist();

Do not consider the functions verifyWishlist() and getCookieVal() they are being used but are not part of the problem. (just to leave the example of the smaller code)

What I got back is this right here in the picture:

inserir a descrição da imagem aqui

The array came ok, the Indice 0 brought normally, the Indice 1, did not count what I put there, I believe because the foreach is not asynchronous...

Could I create this foreach asynchronously?

2 answers

5


I don’t know if you really understand the concept of async and await. If you declare a function as async, all return will be packaged in a Promise, you do not need to return a Promise within an async function.

To resolve all your files so that you don’t have to wait for the resolution of the previous one, just use the native Promise.all method, passing an array of files.

async function generateWishlist() {
    const obj = JSON.parse(getCookieVal('whishlistLEL'));

    const fetchPromises = obj.map(f => fetch(`/api/catalog_system/pub/products/search?fq=productId:${f}`));
    const stream = await Promise.all(fetchPromises);
    const streamPromises = stream.map(s => s.json());
    const products = await Promise.all(streamPromises);

    return [products, products.length];
}

But remember that without treatment, if one of the protocols makes an exception, you will lose the resolution of the others.

1

what was missing was the await in the freight of fetch

example:

async function generateWishlist() {
    var products = [];
    var productLength = 0;
    var lista = [1,2,3,4,5,6,7,8,9,10];
   for (i = 0; i < lista.length; i++) {
   await fetch("https://jsonplaceholder.typicode.com/todos/" + lista[i])
        .then(a => a.json())
        .then(a => {
            products.push(a[0]);
            console.log("Estou passando por aqui hahah, estou te trolando, Lucas")
            productLength++;
        });   
   }
}


generateWishlist();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.