Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

121
Views
No se puede configurar el elemento con la llave en el objeto final

El valor de videoProgress no se devuelve en el documento de objeto final, quiero que se devuelva videoProgress junto con el elemento documentList, pero no lo obtengo, también configuré item.videoProgress pero no lo obtengo en respuesta:

 const document = await Promise.all(documentList.map(async (item) => { const videoCount = await studentProgressModel.find({ gradeId: item.gradeId, userId : item._id, type: 'VIDEO'}).countDocuments(); const totalVideoCount = await videoModel.find({ gradeId: item.gradeId, mediumId: item.mediumId, status: 'ACTIVE' }).countDocuments(); let videoPercentage = 0; if(totalVideoCount > 0) { videoPercentage = (100 * videoCount) / totalVideoCount; } item.videoProgress = videoPercentage; console.log('item', item); return item; }));
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

El problema aquí no es lo que nadie en los comentarios anteriores está discutiendo, el problema es que en realidad no está devolviendo una promesa de su documentList.map, sino que simplemente está escribiendo una función asíncrona allí. Array.map no esperará ningún comportamiento asincrónico, por lo que tan pronto como llegue a await , devuelve un resultado vacío.

Esto se puede solucionar devolviendo promesas en su mapa:

 const document = await Promise.all(documentList.map((item) => { // Removed async here, map is synchronous // Here we *immediately* return a promise so that map can return that to the promise.all return new Promise(async (resolve) => { // Now we can do all our async stuff and promise.all will wait for it :) const videoCount = await studentProgressModel.find({ gradeId: item.gradeId, userId : item._id, type: 'VIDEO'}).countDocuments(); const totalVideoCount = await videoModel.find({ gradeId: item.gradeId, mediumId: item.mediumId, status: 'ACTIVE' }).countDocuments(); let videoPercentage = 0; if(totalVideoCount > 0) { videoPercentage = (100 * videoCount) / totalVideoCount; } item.videoProgress = videoPercentage; console.log('item', item); return resolve(item); // have to use resolve here with our result to resolve the promise. }); }));

Hay otras formas de hacer esto que no involucran un contenedor explícito de nueva promesa, pero pensé que hacía que el comportamiento de la promesa fuera más obvio.

Editar: aquí hay un ejemplo que se puede ejecutar directamente aquí en su navegador, solo he reemplazado las consultas con generadores de números aleatorios asíncronos.

 function randomInteger() { return new Promise((resolve) => { setTimeout(() => { return resolve(Math.floor(Math.random() * 100)); }, 1); }); } async function main() { let documentList = [{}, {}, {}]; const document = await Promise.all(documentList.map((item) => { return new Promise(async (resolve) => { const videoCount = await randomInteger(); const totalVideoCount = await randomInteger(); let videoPercentage = 0; if(totalVideoCount > 0) { videoPercentage = (100 * videoCount) / totalVideoCount; } item.videoProgress = videoPercentage; console.log('item', item); return resolve(item); }); })); console.log('Document results:', document); } main();

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!