Promise async/await not resolved

Asked

Viewed 154 times

0

I am doing . map() in an array, to do a Mongoose/Mongodb query with each element of this array and returns another array with the results.

However, after this process, I try to access the new array with console.log(newArray) and what I print is [Object Promise], and I wanted the results of the queries that should be in this array. NOTE: The queries worked (tested with 1): each one is saved in the value variable. See below:

async function buscarNoBdPorValorContido(model, atributo, valor, resposta){
        var documentos = []
        var valores = valor.split(` `)
        documentos = await valores.map(async valor => {
            const query = model.find({url: {'$in': [new RegExp(`.*${valor}.*`, 'i')]}})
            let value = await query.exec()  //Tudo certo aqui
            return value
        })
     
        console.log('resultado '+documentos) //Imprime "resultado [object Promise]"
           
    }

History summary, I want to use the document array whose contents should be the results of queries. I’ve been at it for hours, I don’t know what else to try. Thank you!

2 answers

1

Promise within a map need to be resolved with Promise.all()

You used await off the map to make all the queries.

In case you would have to involve all the map queries within a Promise.all.

  • 1

    Could you give an example? I don’t think your explanation is clear to someone who isn’t very familiar with.

  • One moment personal, I’ll test.

  • @Rodrigoazevedo Could you show me?

  • @Rodrigoazevedo But each query was being made inside map in Let value = await query.exec(), so do I get this snippet? I simply give Return query inside the map?

  • @Rodrigoazevedo what would await look like? Is that I want to use the solution of the Promises still within this function, to be able to return these values out of it

1


The problem here is that you are returning objects of the type promise for the method map.

Understand that although you are declaring the callback function as async, the method map is not prepared to wait for the resolution of precedents, so it will continue iterating on the other items of the array even before the resolution of its await.

A native Javascript method for waiting for all array resolutions is the Promise.all (as already mentioned).

After generating your Promise array...

var documentos = valores.map(valor => {
    const query = model.find({url: {'$in': [new RegExp(`.*${valor}.*`, 'i')]}})
    return query.exec() // não precisa utilizar await aqui, não terá nenhum efeito prático
})

You can wait for resolution with the method

var resultados = await Promise.all(documentos)
console.log(resultados)

But for your example, I imagine it would be more efficient to create an array of regular expressions and then just make a call to the database:

var valores = valor.split(' ')
var expressoes = valores.map(val => new RegExp(`.*${valor}.*`, 'i'))
var query = model.find({ url: { $in: expressoes } })
var documentos = await query.exec()
  • Got it. Thanks! Not every hero wears kkk cover

  • @Lucas, I did a review of the answer, consider using it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.