Promise.all hangs and does not resolve all languages and applications - Node.js

Asked

Viewed 106 times

0

I’ve had a problem for a while, and I can’t figure out why. In my application I will have an array of ID’s of product categories, and from this array, for each category I want to recover all products by API (paging is required)And for each category, I submit a Promise that only resolves after retrieving all products from that category, through an asynchronous function. For each category I Promise this and add it in an array of files, then use Promise.all by passing this array of files to wait until they have all been solved. But the way I’m doing it, when I have many categories (around 300 up), Promise.all starts to solve all of them very quickly, but most of the time it hangs on the last few times and for the application, without logging in, rejecting any files or anything of the kind, even debugging it crashes the Debugger. If you change the Premomises for await, searching for products by category, one by one, then it goes smoothly. Now that way it won’t... and it would be better that way for performance reasons. HELP PLEASE! Follows the code:

const getAllProducts = require('../endpoints/getProducts');
const getCategories = require('../endpoints/getCategories');

let cont = 0;

module.exports = async (cli) => {    

    console.log('\nBuscando todas as categorias da loja...');

    let listCategoriesId = await getCategories(cli); // 
    

    console.log('Quantidade de categorias obtidas: ' + listCategoriesId.length);

    let arrayPromises = [];
    let allProducts = [];
    
    listCategoriesId.map((categoryId)=>{
        arrayPromises.push( getProductsByCategory(categoryId, cli) );
    });        

    let result = await Promise.all(arrayPromises);

    result.map(products =>{        
        if(products.length > 0){
            allProducts = allProducts.concat(products);
        }
    });
    
    console.log(`\nBusca de produtos finalizada. Total: ${allProducts.length} produtos.`);
    return allProducts;
};

async function getProductsByCategory(categoryId, cli){
    return new Promise( async (resolve, reject)=>{

        try{
            let list_products = [];    
            let products = [];                        
            
            // Variaveis para paginação
            let from = 0; // from = a partir do produto 'x'
            // *Diferença entre ambos não pode ser maior que 50
            let to = 49; // to = até produto x            
            
            // Condição 'do while' para realizar a paginação 
            do {
                products = await getAllProducts(
                    cli,
                    `fq=C:${categoryId}&_from=${from}&_to=${to}` // params
                );     // '/1003/2003/'
                
                if (products.length > 0) {                                 
                
                    list_products = list_products.concat(products);                                    
                
                    from += 50;
                    to += 50;                   
                
                } 
            } while (products.length > 0);
        
            cont++;
            console.log(`(${cont}) categoryId: ${categoryId} - TOTAL DE PRODUTOS RECUPERADOS: ${list_products.length}`);            
            products = null;

            resolve(list_products);

        }catch(ex){
            console.log(ex);      
            reject(ex);
        }
    });
}
No answers

Browser other questions tagged

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