Asynchronous Requests in a Synchronous Way**
기존에는 then() , catch() 를 이용해서 비동기 처리를 했습니다.
-
getposts-
기존 코드
exports.getPosts = (req, res, next) => { const currentPage = req.query.page || 1; const perPage = 2; let totalItems; // 총 item 갯수 세기 Post.find() .countDocuments() .then(count => { totalItems = count; return Post.find() .skip((currentPage - 1) * perPage) .limit(perPage); }) .then(posts => { res.status(200).json({ message: 'Fetched posts successfully.', posts: posts, totalItems: totalItems }); }) .catch(err => { if (!err.statusCode) { err.statusCode = 500; } }); };
-
async / await 적용
exports.getPosts = async (req, res, next) => { const currentPage = req.query.page || 1; const perPage = 2; try { // 총 item 갯수 세기 const totalItems = await Post.find().countDocuments(); const posts = await Post.find() .skip((currentPage - 1) * perPage) .limit(perPage); res.status(200).json({ message: 'Fetched posts successfully.', posts: posts, totalItems: totalItems }); } catch (err) { if (!err.statusCode) { err.statusCode = 500; } next(err); } };
-