Capture the solution of Promise.all() in Javascript

Viewed 55

I'm doing mongoose queries using as parameter the values of an array. So I need to do many queries. And I want to save them in an object out of the promise for to use it later in the same function.

But, the code below just prints "[undefined]". However, I know that the first querie returns a value, because I've tested it alone before, so the array with undefined that returns is wrong. I can't even imagine now what I'm doing wrong.

 async function buscarNoBdPorValorContido(model, atributo, valor, resposta){
        var documentos = []
        var valores = valor.split(` `)
        documentos = await Promise.all(valores.map(async valor => {
                const query = model.find({url: {'$in': [new RegExp(`.*${valor}.*`, 'i')]}}) //Everything working here

            }))

            console.log(documentos) //Prints " [undefined] "       
 }
2 Answers

try returning the query in the async function inside map.

 async function buscarNoBdPorValorContido(model, atributo, valor, resposta){
        var documentos = []
        var valores = valor.split(` `)
        documentos = await Promise.all(valores.map(async valor => {
                return model.find({url: {'$in': [new RegExp(`.*${valor}.*`, 'i')]}}) //Everything working here

            }))

            console.log(documentos) //Prints " [undefined] "       
 }

I've solved like this:

 async buscarNoBdPorValorContido(model, atributo, valor){
        var valores = valor.split(` `)
        var documentos = valores.map(value => {
            const query = model.find({url: {'$in': [new RegExp(`.*${value}.*`, 'i')]}})
            return query.exec() 
        })
        var resultados = await Promise.all(documentos)
        return resultados  

    },
Related