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?
The solution The . map() algorithm applies an async callback to each element of an array, creating promises as it does. However, the returned result by . map() is no promise, but an array of promises.
map. Given a finite Iterable (arrays are Iterable ), or a promise of an Iterable , which produces promises (or a mix of promises and values), iterate over all the values in the Iterable into an array and map the array to another using the given mapper function.
async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
The keyword await is used to wait for a Promise. It can only be used inside an async function. This keyword makes JavaScript wait until that promise settles and returns its result.
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;
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With