Convert array of objects with Promise to normal array

Viewed 2106

After using async-await I am getting the following console log. I am not sure what I am doing wrong.

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

How can I convert this to a normal array of objects?

Like this:

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

I was getting an array with pending promises

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

So I have used setTimeout to get the resolved promise.

Here's the Code:

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);
});

What is the mistake in my code that I am getting an array of promises rather than an array of Objects?

Please Help.

1 Answers

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);
})();

That's how you can use Promise.all to turn an array of promises into an array of values

Related