javascript - 将带有 Promise 的对象数组转换为普通数组

标签 javascript node.js mongodb express mongoose

使用 async-await 后,我​​收到以下控制台日志。我不确定我做错了什么。

[
  Promise {
    {
      categoryName: 'Salary',
      categoryAmount: '35000',
      categoryValue: 'salary',
      categoryId: '5f81c02c8e9fdf62f0422c09'
    }
  },
  Promise {
    {
      categoryName: 'Custom Category',
      categoryAmount: '70000',
      categoryValue: 'custom-category',
      categoryId: '5f841d47f4aaf1462cb6065f'
    }
  }
]

如何将其转换为普通的对象数组?

像这样:

[
      {
        categoryName: 'Salary',
        categoryAmount: '35000',
        categoryValue: 'salary',
        categoryId: '5f81c02c8e9fdf62f0422c09',
      },
      {
        categoryName: 'Custom Category',
        categoryAmount: '70000',
        categoryValue: 'custom-category',
        categoryId: '5f841d47f4aaf1462cb6065f',
      },
    ];

我得到了一个带有待处理 promise 的数组

[ Promise { <pending> }, Promise { <pending> }, Promise { <pending> } ]

所以我使用 setTimeout 来获得已解决的 promise 。

代码如下:

exports.createBudget = async (req, res) => {
  //RevenueCategories
  const revenueData = await req.body.revenueCategories.map(async (el) => {
    //Check if Revenue exists in Revenue Model's Collection, if true get it's _id
    let currentDoc = await Revenue.findOne({
      categoryValue: el.categoryValue,
    }).select('_id');

    //if we have _id then assign it to categoryId property
    if (currentDoc !== null) {
      el.categoryId = await (currentDoc._id + '');
    } 

    //if new Revenue Category then create new Doc and assign it's _id to categoryId property
    else if (currentDoc === null) {
      let newCategData = {
        categoryName: el.categoryName,
        categoryValue: el.categoryValue,
      };

      let newCateg = await Revenue.create(newCategData);
      el.categoryId = await (newCateg._id + '');
    }

    return el;
  });

  setTimeout(async () => {
    console.log('Revenue Data', revenueData);

    const budgetDoc = {
      ...req.body.budgetData,
      revenueData,
    };

    const budget = await Budget.create(budgetDoc);

    res.status(201).json({
      data: {
        status: 'success',
        budget,
      },
    });
  }, 5000);
});

我的代码中有什么错误,我得到的是 promise 数组而不是对象数组?

请帮忙。

最佳答案

async function getValue(x) {
  await new Promise(r => setTimeout(r, 100)); // wait 100 ms
  return x * 2;
}

const promises = [];
promises.push(getValue(1));
promises.push(getValue(2));
promises.push(getValue(3));

// right now, promises is an array of promises -- let's turn that into values:
(async () => {
  const promiseValues = await Promise.all(promises);
  console.log('values:');
  console.log(promiseValues);
})();

这就是如何使用 Promise.all 将 Promise 数组转换为值数组

关于javascript - 将带有 Promise 的对象数组转换为普通数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64319107/

相关文章:

mongodb - 适用于 Mac 的 Docker 和 --host 选项

mongodb - Openshift - 如何运行 mongoexport 以导出 mongodb 集合

带有倒数计时器的 JavaScript

javascript - Logo 和文字无法正确 float

javascript - Nodejs Promise reject 不会转发错误消息

node.js - 无法在 graphQL 中使用 populate 获取嵌套 Mongoose 查询

node.js - NodeJS : Client to Client via Server

mongodb - 同时使用redis和mongodb有意义吗?

javascript - 区分jquery选择器中的文本和复选框

javascript - 将自定义错误消息从 Express JS 发送到 Backbone