Home > Mobile >  How to make CRUD in NodeJS but with async and await?
How to make CRUD in NodeJS but with async and await?

Time:08-27

I have create CRUD but my controller use a lot of callback. I do not know how to use async and await in order to make my code look clean and high performance. I hope anyone can help me and give me some suggestion.

Below is my controller:

// create new course
export function createCourse (req, res) {
  const course = new Course({
    _id: mongoose.Types.ObjectId(),
    title: req.body.title,
    description: req.body.description,
  });
  
  return course
    .save()
    .then((newCourse) => {
      return res.status(201).json({
        success: true,
        message: 'New course created successfully',
        Course: newCourse,
      });
    })
    .catch((error) => {
        console.log(error);
      res.status(500).json({
        success: false,
        message: 'Server error. Please try again.',
        error: error.message,
      });
    });
}

// Get all course
export function getAllCourse( req, res){
  Course.find()
    .select('_id title description')
    .then((allCourse) => {
      return res.status(200).json({
        success: true,
        message: 'A list of all course',
        Course: allCourse,
      });
    })
    .catch((err) => {
      res.status(500).json({
        success: false,
        message: 'Server error. Please try again.',
        error: err.message,
      });
    });
}

// get single course
export function getSingleCourse(req, res) {
  const id = req.params.courseId;
  Course.findById(id)
    .then((singleCourse) => {
      res.status(200).json({
        success: true,
        message: `More on ${singleCourse.title}`,
        Course: singleCourse,
      });
    })
    .catch((err) => {
      res.status(500).json({
        success: false,
        message: 'This course does not exist',
        error: err.message,
      });
   });
}

// update course
export function updateCourse(req, res) {
  const id = req.params.courseId;
  const updateObject = req.body;
  Course.update({ _id:id }, { $set:updateObject })
    .exec()
    .then(() => {
      res.status(200).json({
        success: true,
        message: 'Course is updated',
        updateCourse: updateObject,
      });
    })
    .catch((err) => {
      res.status(500).json({
        success: false,
        message: 'Server error. Please try again.'
      });
    });
}

// delete a course
export function deleteCourse(req, res) {
  const id = req.params.courseId;
  Course.findByIdAndRemove(id)
    .exec()
    .then(()=> res.status(204).json({
      success: true,
    }))
    .catch((err) => res.status(500).json({
      success: false,
    }));
}

Now I want to replace all callbacks with async and await, how to replace and how to use more correctly. I appreciate every help.

CodePudding user response:

// create new course
export async function createCourse(req, res) {
    const course = new Course({
        _id: mongoose.Types.ObjectId(),
        title: req.body.title,
        description: req.body.description,
    });

    try {
        let newCourse = await course.save();
        return res.status(201).json({
            success: true,
            message: 'New course created successfully',
            Course: newCourse,
        });
    } catch (error) {
        console.error(error);
        return res.status(500).json({
            success: false,
            message: 'Server error. Please try again.',
            error: error.message,
        });
    }
}

// Get all course
export async function getAllCourse(req, res) {
    try {
        let allCourse = await Course.find().select('_id title description');
        return res.status(200).json({
            success: true,
            message: 'A list of all course',
            Course: allCourse,
        });
    } catch (error) {
        return res.status(500).json({
            success: false,
            message: 'Server error. Please try again.',
            error: error.message,
        });
    }
}

CodePudding user response:

What you are using is promises and they are used to avoid callbacks hell. It is just a way of calling the callbacks: when you use callbacks you pass the cb function on completion of the task, on the other hand, promises to return the object on which you attach the callbacks thus there is no callback hell.

In the given question, you have used chaining of cbs that are good too and async/await is no magic, they are just syntactic sugar on Promises. They make the code more readable and maintainable.

Let's take an example for createCourse:

export async function createCourse (req, res) {
  try {
     const course = new Course({
     _id: mongoose.Types.ObjectId(),
     title: req.body.title,
     description: req.body.description,
     });
  
     const course = await course.save()
     res.status(201).json({
     success: true,
     message: 'New course created successfully',
     course,
     })
    } catch (error) {
        console.log(error);
      res.status(500).json({
        success: false,
        message: 'Server error. Please try again.',
        error: error.message,
      });
    }
}

Note: always use try/catch with async/await

You can follow the same approach for all the other promises. I recommend you to check this for more details.

  • Related