Dealing with async for each element of an array using async.js module in nodejs

60 Views Asked by At

I need to run a mysql query for each element of the array and add the final results to a response.

Is there no way to do this without adding a setTimeout? I find it odd. Tried everything from async / await , promises , callback , async.js module How to deal with something like this in practice?

Here's what I'm trying to do

let reseach = { }
        let drinktypes = ["1", "2", "3", "4"];

        async.eachSeries( 
            drinktypes, 
            async item => {
              console.log( 'item:', item )
              let query = ` SELECT us.*, 
            fl.web_path, 
            pr.product_name, 
            pr.acidity, 
            pr.drink_type, 
            pr.recmd, 
            pr.raw_ingredient, 
            pr.milling,
            pr.label_image as li,
            fl2.web_path AS wp, 
            pr.alcohol, 
            pr.sake_index, 
            pr.kouboname, 
            pr.kojiname, 
            pr.product_details, 
            pr.memo, 
            pr.type_name, 
            pr.code AS code, 
            pr.raw_ingredient, 
            pr.milling, 
            mk.brewery_name, 
            mk.prefecture 
     FROM   users_scores us 
            join products pr 
              ON us.product_id = pr.pid
            LEFT JOIN fileslabels fl2 ON pr.label_image = fl2.id
            join makers mk 
              ON pr.brewery = mk.mid 
            join product_label pl 
              ON pr.pid = pl.product_id 
            join files fl 
              ON pl.file_id = fl.id 
     WHERE  user_id =\"${req.body.userid}\" 
            AND dranktimes <> 0
            AND pr.drink_type = \"${item}\"`;

            connection.query(query, function (error, results ,fields) {
                    if(!error) {
                    reseach[item] = results[0];

                    } else {
                    throw error;
                    }
                });

              Promise.resolve() // <-- instead of callback
            }, 
            err => {
              console.log('err:', err)
              console.log(reseach) // null 

            setTimeout(function(){ 
                console.log("timeout", reseach); //works
             }, 100);

            }
          )
1

There are 1 best solutions below

3
morozRed On

If I understood your question right then you can simply do this with one SQL query (this query is short just for example):

let query = 'SELECT name FROM users WHERE drink_type IN (?)';
connection.query(query, drinktypes);

Using this