I'm using a JS library to stream server-sent-events on my html page:
<html>
<textarea rows='14' id="value" placeholder="anything you want here"></textarea>
<button type="button" onclick="post(clip)">get</button>
</html>
<script type="text/javascript" src="sse.js"></script>
<script>
url = "http://ac6ba97b046a5dcc677e.elb.us-east-1.amazonaws.com/myapi";
let textArea = document.getElementById("value");
function clip(){
s = textArea.value;
s = s.slice(0, -5);
textArea.value = s;
console.log('hello');
}
function post(callback){
var v = String(textArea.value);
console.log(v);
var source = new SSE(url, {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
payload: v
});
var arr = [];
source.addEventListener('message', function (e) {
arr.push(e.data);
textArea.value = arr.map(el => el || " ").join('');
});
source.stream();
callback();
}
</script>
When the button is clicked, data is sent to a server using POST method and the textbox is populated with data received from the server. I would like to clip the text in the textbox with clip()
after the post()
function is executed. Execution process must be like this:
1. post() logs textArea value
2. source.stream() is executed, textbox populated
3. clip() clips last 5 characters and logs 'hello'
But I instead get this:
1. post() logs textArea value
2. clip() clips last 5 characters and logs 'hello'
3. source.stream() is executed, textbox populated
For some reason clip()
is being executed before source.stream()
even after adding a callback.
The sse.js file that I'm using.
[EDIT] After moving callback()
to the end of 'message' handler, the issue still persists:
function post(callback){
var v = String(textArea.value);
console.log(v);
var source = new SSE(url, {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
payload: v
});
var arr = [];
source.addEventListener('message', function (e) {
arr.push(e.data);
textArea.value = arr.map(el => el || " ").join('');
callback();
});
source.stream();
}
Does anyone know what might be causing this?
question from:
https://stackoverflow.com/questions/65862490/js-sse-callback-isnt-working-with-eventlistener 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…