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
CodePudding user response:
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,
});
}
}
CodePudding user response:
// 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
}
}
CodePudding user response:
If you want to replace cache, then with async, await 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);
});
})
}