Galera, boa noite . Estou com um problema com o uso de Async/Await com o código abaixo.
Quando faço o response.json(locations), o valores de retorno é um objeto sem os locations, pois parece que a função assincrona que retorna os items alterando os locations ainda não foi resolvida. Dai a rota retorna o objeto abaixo Retorno para 2 locations:
[
{ },
{ }
]
Eis o meu código:
locationsRouter.get('/', async (request, response) => {
const { city, uf, items } = request.query
const parsedItems: Number[] = String(items).split(',').map(item => Number(item.trim()))
const locations = await knex('locations')
.join('location_items', 'locations.id', '=', 'location_items.location_id')
.where(function() {
if (items){
this.whereIn('location_items.item_id', parsedItems)
}
})
.where(function() {
if (city && uf) {
this.where({
city: String(city),
uf: String(uf)
})
} else if (city && !uf) {
this.where({city: String(city)})
} else if (!city && uf) {
this.where({uf: String(uf)})
}
})
.distinct().debug(true)
.select('locations.*')
.then((locations) => {
return locations.map( async (location: any) => {
const items = await knex('items')
.join('location_items', {'items.id': 'location_items.item_id'})
.where({'location_items.location_id': location.id})
.select('items.*')
.then((items) => {
return items.map((item: any) => {
return {
id: item.id,
title: item.title,
image_url: staticUrl + item.image
}
})
})
console.log({
...location,
items
})
return {
...location,
items
}
})
})
return response.json(locations)
})
Ao executar o código, é possível ver o print do consile.log com conteúdo que deveria ser retornado:
{
id: 1,
name: 'Recicla Mais',
image: '9a639f79cbf0-tiempo_rapido.jpg',
email: 'reciclamais@gmail.com',
whatsapp: '+5531912340000',
latitude: -23.0003709,
longitude: -43.365895,
city: 'Belo Horizonte',
uf: 'MG',
items: [
{
id: 1,
title: 'Papéis e Papelão',
image_url: 'http://localhost:3333/uploads/papel.png'
},
{
id: 3,
title: 'Óleo de Cozinha',
image_url: 'http://localhost:3333/uploads/oleo.png'
},
{
id: 5,
title: 'Baterias e Pilhas',
image_url: 'http://localhost:3333/uploads/bateria.png'
}
]
}
{
id: 4,
name: 'Recicla Minas',
image: 'fake-image.png',
email: 'reciclalegal@gmail.com',
whatsapp: '+5531912340000',
latitude: -23.0003709,
longitude: -43.365895,
city: 'Uberlandia',
uf: 'MG',
items: [
{
id: 2,
title: 'Vidros e Lâmpadas',
image_url: 'http://localhost:3333/uploads/vidro.png'
},
{
id: 4,
title: 'Resíduos Orgânicos',
image_url: 'http://localhost:3333/uploads/organico.png'
}
]
}
No entanto, a rota não retorna essa resposta. Ela retorna:
[
{ },
{ }
]
Estou meio perdido no uso das funções async/await 🙁 Agradeço desde já se alguém puder dar uma olhada no meu código
Código completo no github: https://github.com/julianojcs/Typescript-with-NodeJs
map
que faz uma query (o problema está nele, aliás, já que omap
está retornando um array de promessas). Mas é importante notar que, mesmo que você corrija esse problema, estará fazendo uma query (ali nomap
) para cada linha retornada pela query principal (o que pode ser vir muito ruim em questão de performance). – Luiz Felipe 1/11/20 às 23:08async/await
depois no mesmo código utilizouthen
? porque? – novic 1/11/20 às 23:11