重构为异步/等待

时间:2018-10-01 06:58:42

标签: node.js express mongoose async-await

我只是在学习如何使用异步/等待,而我正在尝试重构回调以使用它。

我只想知道我是不是做对了...或者有人可以像我在跟10岁的孩子说话一样向我解释它。

这是我正在尝试重构的代码

router.post("/", middleware.isLoggedIn,  async function(req, res) {
//lookup book using id

var username = req.user.username;
var userId = req.user._id;
var available = req.body.available;
var daysToAdd = 2;
var reservedBy = {username: username, userId: userId, available: available};

Book.findById(req.params.id, function(err, book) {
    if (err) {
        console.log(err);
    } else {
        //create new reserve name

        Reserve.create(reservedBy, function(err, reserve) {
            if (err) {
                console.log(err);
            } else {
                reservedBy.username)
                // console.log("new reserves username " + reservedBy.available)
                reserve.returnDate = reserve.borrowDate.setDate(reserve.borrowDate.getDate() + daysToAdd);
                reserve.reserved.id = reservedBy.userId;
                reserve.reserved.username = reservedBy.username;
                // //save review
                reserve.save();
                //connect reserve user to book
                //redirect to book show page
                book.reserves.push(reserve);
                if (book.available < 1) {
                    req.flash("error", "There are no more available books");
                    res.redirect("/library/" + book._id);
                } else {
                    book.available--;
                    book.save();
                    res.redirect("/library/" + book._id);
                }
            }
        });
    }
});

});

这是我到目前为止重构的。

try {
    let book = await Book.findById(req.params.id);
    let reserve = await Reserve.create(reservedBy);

    reserve.returnDate = reserve.borrowDate.setDate(reserve.borrowDate.getDate() + daysToAdd);
    reserve.reserved.id = reservedBy.userId;
    reserve.reserved.username = reservedBy.username;
    reserve.save();

    book.reserves.push(reserve);
    if (book.available < 1) {
        req.flash("error", "There are no more available books");
        res.redirect("/library/" + book._id);
    } else {
        book.available--;
        book.save();
        res.redirect("/library/" + book._id);
    }

} catch(err) {
  req.flash('error', 'Something went wrong!');
  res.redirect('back');
}

0 个答案:

没有答案