我正在尝试使用Express中的res.json()函数返回一些json数据,但是似乎每次都在附加到旧的json对象,而不是每次都返回一个新的json对象。这意味着我正在同一响应对象中接收重复数据。
我的代码如下:
await Promise.all(promises)
.then(responses => res.json(responses))
.catch(error => console.error(error))
返回的数据示例:
[
[data]
]
第二个请求返回的数据样本:
[
[data],
[data(1)]
]
我的代码返回了我想要的响应列表,但是在重复请求相同功能时,新响应将附加到旧响应的数据上并发送回去。这是故意的吗?我在做错什么吗?
edit :这是我上下文的其余代码。我是js和异步编程的新手,所以让我知道我做的事情是否完全错误。
const fetch = require('node-fetch')
const authFunctions = require('./auth')
var bearer_token
const space_id = 11111
let id_promises = []
async function get_category_rooms(category_id)
{
return fetch(`https://url.com/api/${category_id}`,
{
headers:
{
'Authorization': `Bearer ${bearer_token}`
}
}).then(response => response.json())
.then(data => data.map(category => category.items))
.catch(err => console.error(err))
}
async function get_category_ids() {
return fetch(`https://url.com/api/${space_id}`,
{
headers:
{
'Authorization': `Bearer ${bearer_token}`
}
})
.then(response => response.json())
.then(data =>
{
categories = data[0]["categories"].filter(category => category.name !== "category i don't want")
categories.forEach(category_item =>
{
id_promises.push(new Promise((resolve, reject) =>
{
resolve(get_category_rooms(category_item.cid))
}))
})
})
}
async function get_room_bookings(room_id) {
return fetch(`https://url.com/api/${room_id}`,
{
headers:
{
'Authorization': `Bearer ${bearer_token}`
}
})
.then(response => response.json())
.then(data => data)
}
async function get_not_group_room_reservations(req,res)
{
let room_promises = []
if (!await authFunctions.auth_check(bearer_token))
{
console.log('invalid bearer token. changing bearer')
bearer_token = await authFunctions.auth()
}
await get_category_ids()
let rooms = await Promise.all(id_promises)
.then(responses =>
{
let room_ids = responses.flat(2)
room_ids.forEach(room_id =>
{
room_promises.push(new Promise((resolve, reject) =>
{
resolve(get_room_bookings(room_id))
}))
})
})
.catch(error => console.error(error))
await Promise.all(room_promises)
.then(responses => res.json(responses))
.catch(error => console.error(error))
}