我正在使用nodejs和mongodb在一个小型购物网站上工作。我已经能够从数据库中存储和检索数据。但是,我无法使用应该从用户购物车中检索产品的特定功能。产品被检索到 then()块中,但是当我尝试通过对产品执行某些操作来退回或打印产品时,我将输出为Promise {未决}。
在将此问题标记为重复(不是,但是如果您认为是)之前,请至少帮助我解决这个问题。
const productIds = this.cart.items.map(eachItem => {
return eachItem.pid;
}); //to get product IDs of all the products from the cart
const cartData = db.collection('products') //db is the database function and works fine
.find({_id: {$in: productIds}})
.toArray()
.then(products => {
console.log(products); //all the products are printed correctly
products.map(eachProduct => {
return {
...eachProduct,
quantity: this.cart.items.find(eachCP => {
return eachCP.pid.toString() === eachProduct._id.toString()
}).quantity //to get the quantity of that specific product (here eachProduct)
};
})
})
.catch(err => {
console.log(err);
});
console.log('cartData: ', cartData); //but here it prints Promise /{ pending /}
我无法理解为什么我得到 Promise {} 作为输出,尽管我在then()块中成功地从数据库中获取了数据。 抱歉,代码混乱。我是mongodb的新手,对promise的了解也不多。
答案 0 :(得分:1)
Promise#then
不会“等待”,因为程序中的下一条语句将延迟到承诺完成之前。
仅在将您传递给then
的回调的执行延迟到诺言完成之前,它才“等待”。
但是您当前的功能(设置then
的功能)不会阻塞,而是继续立即运行。意味着您传递给then
的函数之外的所有内容都可能会看到诺言仍处于未完成状态。
您可能想要使用async/await
构造,如链接重复线程中所述(例如)。