Let's say I have a button on my web page and an output-field. When I click on the button, an asynchronous function is called several times. Each time, the function returns some data, which I want to send to the output field (and append to the previous data).
Here is the main.js:
$(document).ready(function () {
$("#submitButton").on('click', function () {
$.post(
'/',
{
text: inputField.val(),
depth: $('#depthField').val()
},
function (response) {
let outField = $('#outputField');
let txt = outField.text().trim();
outField.text(txt + "\n new data: " + response);
}
);
});
}
And then I have a index.js:
router.post('/', function (req, res) {
let text = req.body.text;
getHTML(text, function (buf) {
doParse(buf, function (out) {
res.send(out);
})
});
});
getHTML returns some data, which is proceeded by doParse. The doParse also generates some data, which should be parsed back to the output-field.
I guess, the post-method is not the right way, to do this, because it is only called once?
EDIT 1:
The Problem is, that i can only see the first data, which is send by the callback, then i get an
(node:16436) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
EDIT 2:
Principal working of the 2 functions 'getHTML' and 'doParse' :
const getHTML = function(callback) {
for (let j = 0; j < 10; j++) {
callback(j);
}
};
const doParse = function(buf, callback) {
let msg = 'val = ' + buf;
console.log(msg);
callback(msg);
};