JavaScript: Fetching Stream Responses from APIs using ReadableStream
To get a stream response from an API in JavaScript, you can use the Fetch API with the ReadableStream object. Here's an example:
fetch('https://example.com/api/stream')
.then(response => {
const reader = response.body.getReader();
return new ReadableStream({
start(controller) {
function push() {
reader.read().then(({ done, value }) => {
if (done) {
controller.close();
return;
}
controller.enqueue(value);
push();
});
}
push();
}
});
})
.then(stream => {
const decoder = new TextDecoder();
const reader = stream.getReader();
return new Promise((resolve, reject) => {
let data = '';
function read() {
reader.read().then(({ done, value }) => {
if (done) {
resolve(data);
return;
}
data += decoder.decode(value);
read();
}).catch(reject);
}
read();
});
})
.then(data => {
console.log(data); // Do something with the stream data
})
.catch(error => {
console.error(error); // Handle errors
});
This code sends a GET request to an API endpoint that returns a stream of data. It then reads the stream using a ReadableStream object and concatenates the data into a string using a TextDecoder object. Finally, it logs the data to the console. Note that this code is for demonstration purposes only and may need to be adapted to your specific use case.
原文地址: https://www.cveoy.top/t/topic/mlnB 著作权归作者所有。请勿转载和采集!