Promise { } - Trying to await for .map

2019-04-01 01:55发布

I am using .map to map out a new object and to add the old price to the map.

I am using Async/Await with my datamaps, here is what my code looks like:

let datasets = await changes.map(async (data) => {
  let products = {};
  let last = await models.prices.findOne({
    where: {
        productId: data.productId,
        sourceId: data.sourceId
    },
    order: [['createdAt', 'DESC']],
    limit: 1,
    offset: 1
  });

  products.name   = data.product.name;
  products.price  = data.price;
  products.sku    = data.product.sku;
  products.source = data.source.name;
  products.link   = data.link;
  products.diff   = last.price;


  return products;
});

changes are all of the prices changes found in the last 24 hours.

last contains the previous time a price change was found of the particular product.

The return products isn't waiting, so I get a spam of Promise { <pending> } messages. If I use a console.log(last) it's working inside, but I cannot figure out the correct way to slow down the return.

products.diff = last.price is the one piece that needs to fill for this to be valid. Any ideas?

1条回答
放我归山
2楼-- · 2019-04-01 02:25

await awaits on Promises but Array.prototype.map returns a new array of Promises. You need to wrap it with Promise.all

let datasets = await Promise.all(changes.map(async (data) => {
  let products = {};
  let last = await models.prices.findOne({
    where: {
        productId: data.productId,
        sourceId: data.sourceId
    },
    order: [['createdAt', 'DESC']],
    limit: 1,
    offset: 1
  });

  products.name   = data.product.name;
  products.price  = data.price;
  products.sku    = data.product.sku;
  products.source = data.source.name;
  products.link   = data.link;
  products.diff   = last.price;


  return products;
}));
查看更多
登录 后发表回答