Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

127
Visualizações
Not able to set item with the key in the final object

The value of videoProgress is not returned in the final object document, i want videoProgress to be returned along with the documentList item, but i am not getting it, i have set item.videoProgress too but not getting it in response:

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 Respostas
Responde à pergunta

0

The issue here is not what anyone in the comments above is discussing, the issue is that you are not actually returning a promise from your documentList.map, but instead are just writing an async function there. Array.map will not wait for any asynchronous behavior, so as soon as it hits an await it returns an empty result.

This can be fixed by instead returning promises in your map:

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

There are other ways to do this that don't involve an explicit new-promise wrapper, but I figured it made the promise behavior more obvious

Edit: Here's an example which can be run directly here in your browser, I have only replaced the queries with async random number generators.

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda