JavaScript ChatGPT API 调用代码优化:错误处理和性能提升
以下代码示例展示了如何使用 JavaScript 调用 ChatGPT API,并对代码进行了优化,以确保其稳定性和性能。
async function callCHATGPT() {
var url = 'https://free-api.cveoy.top/v2/completions';
var version_ = 'jsjiami.com.v7';
var responseText = document.getElementById('result');
responseText.innerHTML = '';
const prompt = document.getElementById('prompt').value;
const data = JSON.stringify({ 'prompt': prompt });
try {
const response = await fetch(url, {
'method': 'POST',
'headers': {
'Content-Type': 'application/json'
},
'body': data
});
if (response.ok) {
const reader = response.body.getReader();
if (reader) {
let responseTextContent = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
responseTextContent += new TextDecoder().decode(value);
}
responseText.textContent = responseTextContent; // 使用 textContent 替代 innerHTML
} else {
responseText.innerHTML += '读取数据失败';
}
} else {
responseText.innerHTML += 'API 请求失败';
}
} catch (error) {
console.error('调用 API 失败:', error);
responseText.innerHTML += '网络连接失败';
}
}
代码优化说明:
- 错误处理: 添加了
try...catch代码块,用于捕获网络错误或 API 错误,并在错误发生时显示相应的提示信息。 - 读取数据: 对
response.body.getReader()进行判断,避免返回undefined导致的错误。 - 性能优化: 使用
textContent替代innerHTML来更新文本内容,可以提高性能。
建议:
- 在调用 API 之前,检查网络连接是否正常。
- 使用合适的错误处理机制,以便在错误发生时及时通知用户。
- 优化代码结构,提高代码可读性和可维护性。
原文地址: https://www.cveoy.top/t/topic/mx68 著作权归作者所有。请勿转载和采集!