简体   繁体   中英

Mysql node.js async, wait for query to complete

Been trying everything to get this to work specifically the async each method. for (const element of resultsHistory) didn't work either.

I'm trying to modify the result array from a previous query by running a foreach over it and doing a mysql query.

However this needs to wait for the query to complete.

Is there a way to access these results without the setTimeout(function() { } I put manually in order to wait for the query to finish?

        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);


        }

See my answer:

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
    }));
});

Managed to get it working like this, but still not sure if this is the right way.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM