【发布时间】:2021-04-23 19:07:27
【问题描述】:
为什么即使在 getCart() 方法中使用 await 后,我仍然收到待处理的承诺?我的代码在概念上是否有问题?
请帮忙。谢谢!
class User {
constructor(..., cart) {
//...
this.cart = cart; //{items: []}
}
getCart() {
return (async () => {
const products = this.cart.items.map(async (item) => {
const product = await Products.getProductDetail(item.productId); //this returns a promise.
product.qty = item.qty;
return product; //<pending> Promise
});
console.log(products); //<pending> Promise
return products;
})();
}
}
这里是函数调用:
exports.renderCart = (req, res, next) => {
(async () => {
const products = await req.user.getCart(); //req.user is a User class object, ignore it.
console.log(products); //pending promise :(
res.render('shop/cart', { products, pageTitle: 'Cart'});
})();
};
【问题讨论】:
-
在
getCart()中你应该awaitproducts的值。此外,您似乎应该使用Promise.all,因为它是一系列承诺。 -
另外,
getCart和renderCart中的异步 IIFE 似乎完全没有必要。 -
异步函数自动返回一个 Promise。可以从
awaiting 在另一个异步函数中访问返回值 with Promise.then
标签: javascript node.js express promise async-await