用 Async/Await 替换回调
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
用 async/await 替换回调,以提高 JavaScript 代码的可读性和错误处理能力。
在对 Cloud 控制台使用不同参数值时,或通过直接调用 Vertex AI API,您可以直接查询模型,并测试返回的结果。
|
重构此 JavaScript 代码,使用 async/await 而不是回调来处理异步操作。目标是提高代码的可读性和错误处理能力。
function fetchData(url, callback) {
http.get(url, function(response) {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
callback(null, data);
});
}).on('error', (err) => {
callback(err);
});
}
响应
async function fetchData(url) {
try {
const response = await new Promise((resolve, reject) => {
http.get(url, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve(data);
});
}).on('error', reject);
});
return response;
} catch (error) {
throw error; // Re-throw the error to be handled by the caller
}
}
说明:
async 函数:我们将 fetchData 函数定义为 async ,从而允许在其中使用 await 。
try...catch 块:我们将异步操作封装在 try...catch 块中,以处理潜在的错误。
Promise 和 await :
- 我们创建一个
Promise ,以便在完整收到响应后使用数据进行解析。
- 我们使用
await 来暂停函数的执行,直到 Promise 解析完毕。
- 错误处理:
- 如果在
http.get 请求期间发生错误,则系统会调用 Promise 的 reject 函数,从而执行 catch 块。
- 我们使用
throw error 重新抛出错误,以将其传播给调用方。
- 返回值:如果成功,
fetchData 函数会返回提取的数据。
用法:
async function main() {
try {
const data = await fetchData('https://example.com/data');
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
main();
使用 async/await 的好处:
- 提高了可读性:代码更简洁且更易于理解,因为异步流更明确。
- 简化错误处理:
try...catch 块提供了一种明确的错误处理方法。
- 无回调地狱:我们避免使用嵌套回调,使代码更易于维护。
- 更好的控制流:代码执行更具可预测性,因为
await 会暂停函数,直到异步操作完成。
|
型号: |
gemini-1.5-flash-preview-0514 |
温度: |
1 |
输出令牌数量上限: |
8192 |
TopK: |
40 |
TopP: |
0.95 |
|
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2024-05-28。
[{
"type": "thumb-down",
"id": "hardToUnderstand",
"label":"Hard to understand"
},{
"type": "thumb-down",
"id": "incorrectInformationOrSampleCode",
"label":"Incorrect information or sample code"
},{
"type": "thumb-down",
"id": "missingTheInformationSamplesINeed",
"label":"Missing the information/samples I need"
},{
"type": "thumb-down",
"id": "translationIssue",
"label":"翻译问题"
},{
"type": "thumb-down",
"id": "otherDown",
"label":"其他"
}]
[{
"type": "thumb-up",
"id": "easyToUnderstand",
"label":"易于理解"
},{
"type": "thumb-up",
"id": "solvedMyProblem",
"label":"解决了我的问题"
},{
"type": "thumb-up",
"id": "otherUp",
"label":"其他"
}]