【发布时间】:2020-04-20 04:33:19
【问题描述】:
我正在尝试使用 map 在对象数组中返回一个新字段,一旦我这样做,它就会返回空。
预期结果:
[
{
"id": 2,
"name": "awesome stadium",
"opened": "1970-01-01T00:00:00.000Z",
"capacity": "39590.00",
"location": "some awesome",
"team_id": "147ff48e",
"team": {
"name": "some name",
"location": "some location"
}
}
]
代码:
const venues = await connection(VENUE_TABLE)
.limit(LIMIT_PER_PAGE)
.offset((page - 1) * LIMIT_PER_PAGE)
.select('*');
const venuesWithTeam = venues.map(async (element) => ({
...element,
team: await connection('team')
.where('id', element.team_id)
.select('*')
.first(),
}));
return response.json(venuesWithTeam);
我该怎么做才能让它按预期工作?
【问题讨论】:
-
venuesWithTeam将是一个 Promise 数组 - 它不是空的 - 它只是空的,因为您正在尝试将 Promise 转换为 JSON - 这不会产生任何结果 -
试试
const venuesWithTeam = await Promise.all(venues.map .... etc)
标签: javascript node.js express async-await knex.js