使用Node.js中的async.js模块处理数组的每个元素的异步

时间:2018-11-29 12:33:19

标签: node.js loops asynchronous node-async

我需要对数组的每个元素运行mysql查询,并将最终结果添加到响应中。

不添加setTimeout是否没有办法做到这一点?我觉得很奇怪。尝试了async / await,promise,callback,async.js模块中的所有内容 在实践中该如何处理?

这就是我想要做的

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 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,那么您只需使用一个SQL查询即可完成此操作(例如,该查询很短):

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

使用this