I have this streaming API endpoint:
https://step3-ndjson-stream-api-demo.glitch.me/
I try to render with can.js NDJSON stream and following the example got some success output to console.log but only the first object.
Here's my app.js (truncated):
const AppViewModel = DefineMap.extend("AppViewModel", {
// misc. properties, then
get streamFunct(){
return fetch(
'https://step3-ndjson-stream-api-demo.glitch.me/'
).then(function(response){
return ndjsonStream( response.body );
}).then( ( streamData ) => {
const reader = streamData.getReader();
let read;
reader.read().then( read = ( result ) => {
if ( result.done ) {
return;
}
console.log( result.value );
streamData.getReader().read().then( read );
} );
} );
}
});
And here's a snippet from my index.stache:
<p>Stream Data: <strong>{{streamFunct}}</strong></p>
And my console developer view (note the successful first call):
I think I have to handle the promise object in the index.stache but not sure... Thank you for looking.
UPDATE
Finally I'm able to get the streamed data:
get streamFunct(){
return fetch(
'https://step3-ndjson-stream-api-demo.glitch.me/'
).then(function(response){
return ndjsonStream( response.body );
}).then( ( streamData ) => {
//retain access to the reader so that you can cancel it
const reader = streamData.getReader();
const listResult = document.querySelector('.displayResult ul')
let read;
reader.read().then( read = ( result ) => {
if ( result.done ) {
console.log('Failed to find match');
return;
}
const chunk = result.value;
let listItem = document.createElement('li');
listItem.textContent = chunk.user;
listResult.appendChild(listItem);
return reader.read().then(read);
} ).catch ((error) => {
console.log(error);
});
} );
}
And modify my index.stache:
<p>Stream Data:</p>
<div class="displayResult">
<ul>
</ul>
</div>
But I still got errors/warnings:
UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
[DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Failed promise: TypeError: response.getReader is not a function
Does anyone know how to clear them?