承诺 { <pending> } 错误,即使在到达 then() 块后



我正在使用nodejs和mongodb在一个小购物网站上工作。我已经能够从我的数据库中存储和检索数据。但是,我无法让这个特定的功能工作,它应该从用户购物车中检索产品。产品被检索到then((块中,但是当我尝试通过在产品中执行一些操作来返回或打印产品时,我得到的输出为 Promise { pending }。

在将此问题标记为重复之前(它不是,但如果您认为是(,至少帮助我解决这个问题。

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#then不会"等待",因为程序中的下一条语句将被延迟到承诺完成。

它"等待"的意思是,你传递给then的回调的执行被延迟到承诺完成。

但是您当前的函数(设置then的函数(不会阻塞并立即继续运行。这意味着您传递给then的函数之外的所有内容都可能看到尚未完成状态的承诺。

您可能希望使用async/await构造,如链接重复线程中所述(例如(。

最新更新