Fetching and Displaying Data from a Stream API Using JavaScript
This code snippet demonstrates how to fetch data from a stream API using JavaScript. Here's a breakdown of the process:
-
Constructing the URL:
const url = 'http://127.0.0.1:8000/api/chat-gpt/' + prompt;This line creates the URL for the API endpoint, dynamically including the user's
promptas a parameter. -
Fetching the Data:
fetch(url) .then(response => { // ... }) // ...fetchis used to send a request to the API. The response is then handled by the.thenmethod. -
Handling the Response Stream:
const reader = response.body.getReader(); return new ReadableStream({ start(controller) { function read() { reader.read().then(({done, value}) => { // ... }); } read(); }, });The
response.bodyrepresents the stream of data. We create a newReadableStreamto manage reading chunks of data from the stream. Thereadfunction continuously reads chunks from thereader, enqueues them into thecontroller, and recursively calls itself until the stream is complete. -
Decoding the Data:
const reader = stream.getReader(); return new Promise((resolve, reject) => { function processText({done, value}) { // ... } reader.read().then(processText); });A new
Promiseis used to handle the asynchronous processing of the stream. Each chunk read from the stream is decoded usingTextDecoder('utf-8').decode(value)and then logged to the console and appended to theresponseTextelement.
Error Handling
To handle errors in this code, you can add a .catch() method after the .then() chain. For example:
const url = 'http://127.0.0.1:8000/api/chat-gpt/' + prompt;
fetch(url)
.then(response => {
// ...
})
.then(stream => {
// ...
})
.catch(error => {
console.error(error);
// handle the error here, e.g. display an error message to the user
});
This will catch any errors that occur during the fetch request, the stream processing, or the promise chain itself. You can then handle the error in whatever way makes sense for your application.
原文地址: https://www.cveoy.top/t/topic/mDeO 著作权归作者所有。请勿转载和采集!