javascript - 如何访问从 Promise.all() 返回的密钥
问题描述
如何访问从Promise.all()
.
我想遍历整个数组并获得从每个承诺返回的标题,但我无法访问Promise {}
,然后是里面的任何对象。
[
Promise {
{
_id: 5e09e4e0fcda6f268cefef3f,
title: 'dfgfdgd',
shortDescription: 'gfdgdfg'
},
qty: 1
},
Promise {
{
_id: 5e09e507fcda6f268cefef40,
title: 'Test product',
shortDescription: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the '
},
qty: 1
},
Promise {
{
_id: 5e09e507fcda6f268cefef40,
title: 'Test product',
shortDescription: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the '
},
qty: 3
}
]
编辑
这是创建承诺数组的代码
const userId = req.user._id;
try {
const user = await User.findById(userId);
const { inCart } = user;
const results = [];
for (let i = 0; i < inCart.length; i += 1) {
results.push(Product.findById(inCart[i].itemId, 'title shortDescription').exec());
}
await Promise.all(results);
for (let i = 0; i < results.length; i += 1) {
results[i].qty = inCart[i].qty;
}
return res.render('shop/cart', { items: results });
} catch (error) {
console.log(error)
}
解决方案
我想Promise.all
没有机会弄清楚哪个已经调用了resolve
里面的函数。
从Promise.all()
文件中指出:
Promise.all() 方法返回一个 Promise,当所有作为 iterable 传递的 Promise 都已实现或 iterable 不包含任何 Promise 时,该 Promise 就会实现。它以拒绝的第一个承诺的原因拒绝。
在我的示例中,我创建了Promise
具有更简单对象的元素,例如{ title: 'first' }
为了更好地表示。
为了实现您的目标,您需要处理每个Promise
已解决的状态,例如,forEach
就像在我的解决方案中一样,而不是使用Promise.all()
. 通过then
在每次迭代中使用,您可以访问已解析的对象属性。
相反,您可以执行以下操作 - 显然您需要应用于您的结构:
const promises = [
new Promise(resolve => {
setTimeout(() => {
resolve({ title: 'first' })
}, 1200)
}),
new Promise(resolve => {
setTimeout(() => {
resolve({ title: 'second' })
}, 800)
}),
new Promise(resolve => {
setTimeout(() => {
resolve({ title: 'third' })
}, 2400)
}),
new Promise(resolve => {
setTimeout(() => {
resolve({ title: 'fourth' })
}, 3200)
}),
];
Promise.all(promises).then(() => console.log('all finished'));
promises.forEach(p => p.then(d => console.log(`${d.title} finished`)));
我希望澄清和帮助!
推荐阅读
- ruby-on-rails - 如何处理带有隐藏复选框的滑块
- python - Pycharm:无法导入 lightfm
- ruby-on-rails - 是否可以通过使用 ruby on rails 来执行二进制文件
- android - 查询包含子集合的文档
- php - 当日期字段中包含时间和日期时,获取两个日期之间的 SQL 数据
- c# - Winform 控件成为其他控件的子控件,而不是添加到窗体中。
- c - 使用 CMake 时如何阻止我的 .exe 消失
- reactjs - webpack react开发模式
- objective-c - 目标C中的参数如何传递?
- google-cloud-ml - GCP cloud ml-engine 启动作业问题