问题
I'm building a post request API using Express and I would like to return a JSON response back to the client containing an array of each record the provided, with an additional boolean attribute to show whether the record was successful or not.
router.post('/api/v1/test', (req, res) => {
const request = req.body.partners
const client_response = {}
client_response.partners = []
function Record_response(name, tech, accept) {
this.name = name;
this.tech = tech;
this.accepted = accept;
}
request.forEach(async(record) => {
try{
const rec = new testing({
name: record.name,
tech: record.tech
})
const a1 = await rec.save()
var data = new Record_response(record.name, record.tech, true)
client_response.partners.push(data)
}catch(err){
var data = new Record_response(record.name, record.tech, false)
client_response.partners.push(data)
}
})
res.json(client_response)
});
I want the JSON output to look like this:
{
"partners": [
{
"name":"test_name1",
"tech": "test_tech1",
"accepted": "true"
},
{
"name":"test_name2",
"tech": "test_tech2",
"accepted": "false"
}
]
}
This is the current output:
{
"partners": []
}
回答1:
As I've just answered in other similar question, the problem is the data is being collected, but it's being sent before it's joined up together.
As you do request.forEach(async (record) => {, the async part tells your code not to wait, so even before the request.forEach loop is done, res.json(client_response) runs, when client_response is yet just an empty array.
There are dozens of ways you can solve it. I can even think of the dumbest ones.
But here comes a good one:
// Start by saying your whole function is an async one
router.post('/api/v1/test', async (req, res) => {
... // (Your code comes here)
// A better way to do the loop
//for(const record of request){
// Object deconstruction is awesome
for(const { name, tech } of request){
try{
const rec = new testing({ name, tech })
// Here, now all the function waits for this next line
const a1 = await rec.save()
var data = new Record_response(name, tech, true)
client_response.partners.push(data)
}catch(err){
var data = new Record_response(name, tech, false)
client_response.partners.push(data)
}
}
// So the client_response has finally something!
res.json(client_response)
});
来源:https://stackoverflow.com/questions/65617747/appending-objects-to-an-array-within-a-parent-object