首页 > 解决方案 > 如何访问从 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)
  }

标签: javascriptobject

解决方案


我想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`)));

我希望澄清和帮助!


推荐阅读