I have function queryIterator
that returns async object value called result
, I use a call back function to send result
to the browser via res.send()
.
Error: (node:3497) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I think im getting error because i am consistently resending a response to the browser when the header is already set, correct?
How can I continuously stream data to the client browser from express server?
router.post('/', async (req, res) => {
// Assign first query
searchedT = req.body.searchTerm;
queries.push(req.body.searchTerm);
// Invoke the async iterator
console.log("start....");
const results = await queryIterator(queries, async function(result) {
console.log("--->" + await result);
res.send(await result);
});
// res.send(result);
});
async function queryIterator(queries, callback) {
for await (const result of queryGenerator()) {
// console.log('Iterating... ', result);
// console.log(`On Queue Searches #${++counter}: `, queries);
// console.log(`On Queue Searches LAST #${++counter}: `, queries[queries.length-1]);
if (!queries.length) {
console.log("query length is zero");
return result;
}
callback(result);
// return result;
}
}