Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

node.js - How can I rewrite this nested callback hell functions with the async await/promises?

I am new to Nodejs. I have to perform some set of functions one after one since the tasks are dependent on each other. So I thought to use the callback functon way where I am calling another callback means nested callbacks one after other in order to achieve the results.

But then after somewhere I came to know about the Callback Hells and that should be avoided. So then I am now confused then how to use promises/ async-await to achieve that?

And also how its different than the nested callbacks since in promises also then next prmise is called only when the first promise is resolved hence it has too the nested callback nature.

Please someone can correct me what I am doing wrong?

    router.route('/addTasks-approve').get(function(req, res) {
    
if(req.query.text == 'Approved')
                     {
                      User.updateMany({'Addtasks.commonID':req.query.id},
                         {$set: {"Addtasks.$.width" :'250px',
                          "Addtasks.$.height" :'32px',
                          "Addtasks.$.background" :'linear-gradient(45deg, #0f3443, #34e89e)',
                          "Addtasks.$.border_radius" :'10px / 5px',
                         "Addtasks.$.status" :req.query.text}},
                        function (error, success) {
                              if (!error) {
                                console.log("Approved color set!");
                                User.findOne({tag:'Admin','Addtasks.commonID':req.query.id},function (error, dataAdmin) {
                                      if (error) {
                                          console.log("error = "+ error);
                                          res.end('{"msg" : "Some error occurred", "status" : 700}');
                                      }
                                      else {
                                        dataAdmin.Addtasks.forEach(element => {
                                          if(element.commonID == req.query.id)
                                          {
                                     User.findOneAndUpdate({tag:'Client','Addtasks.commonID':req.query.id},
                                     {$push: {'Addtasks.$.Bigpaths4Clients':{$each : element.Bigpaths4Clients}},
                                      $set: {"Addtasks.$.background" :'linear-gradient(45deg, #1E6305, #BDFF00)',
                                             "Addtasks.$.status" :'Done'}},
                                        function (error, data) {
                                              if (error) {
                                                console.log("error = "+ error);
                                                res.end('{"msg" : "Unable to add the Task", "status" : 700}');
                                              }
                                              else {
                                                console.log("Addtasks added to Client's dashboard succesfully");
                                                sendMails2Client(data.email, element.topic, 'In Progress', 'Done');
                                                sendMails2User(dataAdmin.email, element.topic, 'Done', 'Approved');
                                                User.findOne({tag:'Admin','Addtasks.commonID':req.query.id},function (error, dataWriter) {
                                                      if (error) {
                                                          console.log("error = "+ error);
                                                          res.end('{"msg" : "Some error occurred", "status" : 700}');
                                                      }
                                                      else {
                                                        sendMails2User(dataWriter.email, element.topic, 'Done', 'Approved');
                                                        res.end('{"success" : "success", "status" : 200}');
                                                      }
                                                    })
                                              }
                                      })
                                    }
                                  });
                                }
                              });
                              }
                              else {
                                res.end('{"msg" : "Unable to set the status and color for Approved", "status" : 700}');
                              }
                            });
                          }                 
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can use this article, it's about Callback vs Promise vs async/await with example... but I prefer asyn/await

your code base on asyn/await:

router.route("/addTasks-approve").get(async (req, res) => {
  if (req.query.text == "Approved") {
      try {
        let resUpdate = await User.updateMany(
            { "Addtasks.commonID": req.query.id },
            {
              $set: {
                "Addtasks.$.width": "250px",
                "Addtasks.$.height": "32px",
                "Addtasks.$.background": "linear-gradient(45deg, #0f3443, #34e89e)",
                "Addtasks.$.border_radius": "10px / 5px",
                "Addtasks.$.status": req.query.text,
              },
            }
          );
            console.log("Approved color set!");
            let dataAdmin = await User.findOne({
              tag: "Admin",
              "Addtasks.commonID": req.query.id,
            });
      
            dataAdmin.Addtasks.forEach(async (element) => {
              if (element.commonID == req.query.id) {
                let data = await User.findOneAndUpdate(
                  { tag: "Client", "Addtasks.commonID": req.query.id },
                  {
                    $push: {
                      "Addtasks.$.Bigpaths4Clients": {
                        $each: element.Bigpaths4Clients,
                      },
                    },
                    $set: {
                      "Addtasks.$.background":
                        "linear-gradient(45deg, #1E6305, #BDFF00)",
                      "Addtasks.$.status": "Done",
                    },
                  }
                );
      
                console.log("Addtasks added to Client's dashboard succesfully");
                await sendMails2Client(data.email,element.topic,"In Progress","Done");
                await sendMails2User(dataAdmin.email,element.topic,"Done","Approved");
                let dataWriter = await User.findOne({
                  tag: "Admin",
                  "Addtasks.commonID": req.query.id,
                });
                await sendMails2User(dataWriter.email, element.topic, "Done", "Approved");
                res.end('{"success" : "success", "status" : 200}');
              }
            });
      } catch (error) {
          console.log(error)
      }
    
  }
});

but for error handling you should use try/catch for any part of your code that an error may occur


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...