在这一刻我有一个问题。如何在.map()之外推送大量数据。
我需要在const todo = []
中推送大量数据并查看.map()codigoP.map
我尝试使用.promise
,但我不知道如何在推送大量数据时如何实现:
const todo = [];
let dateNow = moment();
let diferencia = 0;
codigoP.map(async (item)=> {
const listaPrecio = await models.listas_precios.findOne({
where: {
producto_id: item.id,
cliente_id: empresa.id
}
});
let precioIva = 0;
if (listaPrecio) {
precioIva = listaPrecio.iva;
}
cant += parseInt(detDevolucion.cantidadProducto);
precioTotal = detDevolucion.precio_producto * parseInt(detDevolucion.cantidadProducto);
const totalIva = precioTotal + precioIva;
total += totalIva;
totalConIva += precioTotal;
ivaTotal += precioIva;
let fechaVencimiento = moment(item.fechaVencimiento).utc().toDate();
diferencia = dateNow.diff(fechaVencimiento, 'days');
todo.push({
codigo: item.codigo,
nombre: item.nombre,
vidaUtil: diferencia,
lote: detDevolucion.lote_id,
cantidad: detDevolucion.cantidadProducto,
precio: numeral(detDevolucion.precio_producto).format('$0,0.00'),
precioTotal: numeral(precioTotal).format('$0,0.00'),
iva: numeral(precioIva).format('$0,0.00'),
totalIva: numeral(totalIva).format('$0,0.00'),
observacion: detDevolucion.observacion,
fechaVenc: dateFormat(item.fechaVencimiento, "yyyy-mm-dd")
});
console.log('todo: ', todo);// **this works, return the values**
diferencia = 0;
});
console.log('todo: ', todo); //**this return todo [], empty array, this is my problem.**
答案 0 :(得分:1)
你可以尝试这样的事情,正如我们上面讨论过的那样。 Map返回一个新数组并返回每次迭代的对象。
编辑:您可以尝试使用Promise.all在返回之前解析承诺。
let dateNow = moment();
let diferencia = 0;
const todo = await Promise.all(codigoP.map(async (item)=> {
const listaPrecio = models.listas_precios.findOne({
where: {
producto_id: item.id,
cliente_id: empresa.id
}
});
let precioIva = 0;
if (listaPrecio) {
precioIva = listaPrecio.iva;
}
cant += parseInt(detDevolucion.cantidadProducto);
precioTotal = detDevolucion.precio_producto * parseInt(detDevolucion.cantidadProducto);
const totalIva = precioTotal + precioIva;
total += totalIva;
totalConIva += precioTotal;
ivaTotal += precioIva;
let fechaVencimiento = moment(item.fechaVencimiento).utc().toDate();
diferencia = dateNow.diff(fechaVencimiento, 'days');
return {
codigo: item.codigo,
nombre: item.nombre,
vidaUtil: diferencia,
lote: detDevolucion.lote_id,
cantidad: detDevolucion.cantidadProducto,
precio: numeral(detDevolucion.precio_producto).format('$0,0.00'),
precioTotal: numeral(precioTotal).format('$0,0.00'),
iva: numeral(precioIva).format('$0,0.00'),
totalIva: numeral(totalIva).format('$0,0.00'),
observacion: detDevolucion.observacion,
fechaVenc: dateFormat(item.fechaVencimiento, "yyyy-mm-dd")
};
//console.log('todo: ', todo);// **this works, return the values**
//diferencia = 0;
}));
console.log('todo: ', todo);