hamidreza nikoonia
hamidreza nikoonia

Reputation: 2165

Synchronous and asynchronous vs callback in mongoose

hi guys i am new in node and have this simple question , what is difference between this two sniped

Note: i know async / await functionality and also in front-end application it is best practice for handle async action but in node in working with mongoose i want know which approach better for handle

first solution

// for example we pass this function as controller to route handler

exports.myController = async (req, res, next) => {

try {
     const data = await Model.find();
     const some = await new Model(data).save();
   } catch(e) {

    next(e);
 }
}

second solution

exports.myController = (req, res, next) => {

 const data = Model.find((err, data_) => {

  const some = new Model(data_);
  some.save((err, result) => {
  ....
})

});

}


i want to know when i have an error from mongoose , in second way can throw error like this

// in callback function 

if (err) {

throw Error();

}

but how can i handle this in async/await solution

Upvotes: 0

Views: 154

Answers (1)

Shorbagy
Shorbagy

Reputation: 534

you simply throw it or log it in your catch block:

try {
     const data = await Model.find();
     const some = await new Model(data).save();
   } catch(e) {
     throw e; 
     next(e);
 }

the async/await is working like promises but without no nesting callbacks and it throws an error synchronous to what errors first and stop from executing the other lines.

Based in your edited Note:
you should always go for the async solution way in nodejs or even for anything related to javascript it's the best composable and reusable solution.

Upvotes: 1

Related Questions