I'm fetching nested object data. I can get that object data on console but when I try to get that data like return res.json(imageObject)
I only get first key value pair of that object. This is the error to the console. UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
. Console data is like this { bigImage: 'https://url.com' }
router.get("/", async(req, res) => { //...fetch data if (mediaData.type === "type1") { let allData = await mediaData.media; allData.map(async(Data) => { if (Data.imageType === "big") { let bigImage = await Data.url; let imageObject = { bigImage }; console.log(imageObject); return res.json(imageObject); } }); } });
You are using res
inside a .map
, which will trigger it once for every item in the array you're iterating.
You can't do that. You can only use res
once for each req
, because you're replying to the browser. If you use it more than once, you get this error, which means it's already been used and you have already replied.
Solution : use res
once, not inside a map
.
Also, .map
is useless here, because you're not interested in the result it produces. You should use forEach
or even better, a for
loop (which is breakable on condition).
You should use for..of
.
It will stop the execution of your function at the return statement
router.get("/", async(req, res) => {
//...fetch data
if (mediaData.type === "type1") {
let allData = await mediaData.media;
let pendingResult = allData.filter(data => data.imageType === "big").map(async item => {
let bigImage = await item.url;
return { bigImage }
});
let result = await Promise.all(pendingResult);
res.json(result);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.