Mysql node.js异步,等待查询完成

时间:2018-11-04 19:17:26

标签: javascript mysql node.js async-await async.js

尝试一切使此方法特别有效地使每种方法异步。 for(resultsHistory的const元素)也不起作用。

我正在尝试通过在其上运行foreach并执行mysql查询来修改前一个查询的结果数组。

但是,这需要等待查询完成。

有没有一种方法可以不用我为了等待查询完成而手动设置的setTimeout(function(){}来访问这些结果?

        function getUserLikes(params, callback) {
            var usersArrayCat = [];
            console.log(`length of array ${params.length}`)
                                // 1 here means 1 request at a time
            async.eachLimit(params, 1, function (element, cb) {
                element.liked = 0;
                var queryLiked = `SELECT * from users_likes WHERE user_id = \"${req.body.userid}\" AND product_id = \"${element.product_id}\"`;
                connectionPromise.query(queryLiked, function (err, result) {
                    if (!result) {
                    } else if (result.length == 0) {

                    } else {
                        element.liked = result[0].userlike;

                        usersArrayCat.push(element);
                      //  console.log(usersArrayCat);
                        cb();
                    }
                })
            }, function (err) {
                if (err) return callback(err);
                callback(null, usersArrayCat)
            });
        };

    getUserLikes(resultsHistory, function (e) {
    console.log(e);
       });     



        if(!res.headersSent) {

            setTimeout(function() {  

            res.send(JSON.stringify({"status": 200 ,"error": null, "top3":resultsHistory}));
            }, 150);


        }

2 个答案:

答案 0 :(得分:0)

查看我的答案:

function getUserLikes(params, callback) {
    var usersArrayCat = [];
    console.log(`length of array ${params.length}`)
    // 1 here means 1 request at a time
    async.eachLimit(params, 1, function (element, cb) {
        element.liked = 0;
        var queryLiked = `SELECT * from users_likes WHERE user_id = \"${req.body.userid}\" AND product_id = \"${element.product_id}\"`;
        connectionPromise.query(queryLiked, function (err, result) {
            if (!result) {
            } else if (result.length == 0) {

            } else {
                element.liked = result[0].userlike;

                usersArrayCat.push(element);
                //  console.log(usersArrayCat);

            }
            cb();
        })
    }, function (err) {
        if (err) return callback(err);
        callback(null, usersArrayCat)
    });
};

getUserLikes(resultsHistory, function (e, usersArrayCat) {
    if (e) {
        console.log(e);
        return res.send({status: 400, error: e}); // your error response
    }
    console.log(usersArrayCat); // your usersArrayCat with liked property
    res.send(JSON.stringify({ // why your need return a string intead of json object ???
        "status": 200,
        "error": null,
        "top3": usersArrayCat // I think return `usersArrayCat` is a right way
    }));
});

答案 1 :(得分:0)

设法使它像这样工作,但仍不确定这是否正确。

async function getUserLikes(resultsHistory) {
    for (const element of resultsHistory) {
        element.liked = 0;
        let queryLiked = `SELECT * from users_likes WHERE user_id = \"${req.body.userid}\" AND product_id = \"${element.product_id}\"`;
        let liked = await conn2.query(queryLiked);

        if (liked[0]) {
            element.liked = liked[0].userlike;
        }        
    }
    if(!res.headersSent) {
        conn2.release();     
        let newres = resultsHistory.sort(
            firstBy(function (v1, v2) { return v2.rating - v1.rating; })
             .thenBy(function (v1, v2) { return v2.dranktimes - v1.dranktimes; })
        ).filter( function(history) {             
            return history.event === eventName;
        }).slice(0, 3);

       res.send({"status": 200 ,"error": null, "top3":newres});       
    }
}

getUserLikes(resultsHistory);