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

130
Visualizações
Node | Promise not finishing

I am trying to fetch data of different collections from MongoDB. I do this with Node.js and promises. Here is some basic code:

await Promise.all(
        ["a", "b", "c"].map(async (collection) => {
            const query: any = { "_id": { $in: ids} }
            // I just use toArray for demonstration purposes
            const data = await this.db!.collection(collection).find(query).toArray()
            for (let i = 0; i < data.length; i++) {
                const document = data[i]
                // Do something...
            }
            console.log(collection)
            return true
        })
    )
 console.log("done")

I do this for eight collections (a, b, ..., h). The data gets fetched from the database and processed correctly in an acceptable amount of time. Then it prints the name for each collection. But it doesn't continue. It doesn't finish the promise and go to the done log.

The method gets called in a JS-Worker task. What could be the problem here? I never had problems with promises and bigger amount of data yet.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is actually a synchronous execution. It will not go to the next collection until the previous db call is finished. The arrow function should return a promise instead.

The solution is to rearrange the code in this way-

async function callDb(collection) {
    const query: any = { "_id": { $in: ids} }
    // I just use toArray for demonstration purposes
    const data = await this.db!.collection(collection).find(query).toArray()

    for (let i = 0; i < data.length; i++) {
        const document = data[i]
        // Do something...
    }
    console.log(collection)
    return true
}

await Promise.all(
    ["a", "b", "c"].map(callDb)
)

console.log("done")
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