user19786314
user19786314

Reputation:

How to use async and await to replace THEN and CATCH in NodeJS?

I have a controller to create new Course but i wanna know how to can i use async and await in order to replace then and catch Here is my code:

// 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 cause created successfully',
        Course: newCourse,
      });
    })
    .catch((error) => {
        console.log(error);
      res.status(500).json({
        success: false,
        message: 'Server error. Please try again.',
        error: error.message,
      });
    });
}

I hope anyone can show me and help me how to use async and await

Upvotes: 0

Views: 1671

Answers (3)

dark.magician
dark.magician

Reputation: 51

If you want to replace cache, then with async, await you will have to use promises. This is example how i would structure code above.

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

  try {
    const newCourse = await create(course);

    return res.status(201).json({
      success: true,
      message: 'New cause created successfully',
      Course: newCourse,
    })
  } catch (error) {
    return res.status(500).json({
      success: false,
      message: 'Server error. Please try again.',
      error: error.message,
    })
  }
}

function create(course) {
  return Promise((resolve, reject) => {
    return course
      .save()
      .then((newCourse) => {
        return resolve(newCourse);
      })
      .catch((error) => {
        return reject(error);
      });
  })
}

Upvotes: 1

asportnoy
asportnoy

Reputation: 2534

// Make sure to add the async keyword
export async function createCourse (req, res) {
  // ...

  try {
    const newCourse = await course.save();
    // Do something with the created course, works like the .then function
  } catch (err) {
    // Do something with the error, works like the .catch function
  }
}

Upvotes: 1

gpdevpro
gpdevpro

Reputation: 36

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

Upvotes: 2

Related Questions