Search code examples
node.jspostgetpromiseejs

How do I use Promise.all to make it work?


My main purpose is to make this function work:

Whenever users click the "likes" button or "dislikes" button, it will post new data to server, then the server is supposed to update both of number of "likes" and "dislikes" in database. After that, it will redirect to another URL to get the previous page with new updated number of "likes" and "dislikes".

During the process, because of JS's asynchronous effect, I decide to use Promise.all. But I was stuck in that part (marked by 3 question marks in my code). Could anybody help me to revise it or give me any better suggestion?

Here is my Node.js codes:

app.post("/searchresult/comments/likes", function(req, res) {
var likes = req.body.likes;
var dislikes = req.body.dislikes;
var Text = req.body.text;
var Arr = [likes, dislikes];

Promise.all(Arr.map(function (attribute) {
    return new Promise(function (resolve, reject) {
        comments.update({text: Text}, {$set: {???: attribute}}, function(err){
            if (err) {
                console.log(err);
            } else {
                console.log("Update successfully!");
                resolve(comments);
            }
        });
}).then(function(r){
    console.log("DONE!");
    res.redirect("/searchresult");
})
}));
});

//************************************************* Update! ************************************************//

Thanks so much to Ganesh Karewad, James and dasfdsa. I have made it work properly.


Solution

  • Use array of object instead of direct values like var Arr = [{key:'likes',value:likes},{key:'dislikes',value:dislikes}];

     app.post("/searchresult/comments/likes", function(req, res) {
        var likes = req.body.likes;
        var dislikes = req.body.dislikes;
        var Text = req.body.text;
        var Arr = [{key:'likes',value:likes},{key:'dislikes',value:dislikes}];
    
        Promise.all(Arr.map(function (attribute) {
        return new Promise(function (resolve, reject) {
            comments.update({text: Text}, {$set: {attribute.key: attribute.value}}, 
             function(err){
                if (err) {
                 // reject or log error according to need
                    console.log(err);
                 // reject(err);
                } else {
                    console.log("Update successfully!");
                    resolve(comments);
                 }
              });
          }).then(function(r){
           console.log("DONE!");
           res.redirect("/searchresult");
          }).catch(function(err){
          // reject or log error according to need
          // console.log(err);
           reject(err);
          })
         }));
        });