【发布时间】:2021-10-23 11:08:02
【问题描述】:
尝试通过错误检查发出 API 请求,然后能够在异步函数之外使用来自 API 的数据。这正在返回一个未决的承诺。不知道如何从 API 中获取可用数据,然后我可以在整个程序中进一步使用。有什么建议吗?
const fetch = require('node-fetch')
const url = 'https://employeedetails.free.beeceptor.com/my/api/path'
async function getData(url){
try {
const response = await fetch(url)
if (!response.ok) {
throw new Error ("why did I become a software engineer?");
}
else {
return await response.json();
}
}
catch (error) {
console.log(error);
}
}
const data = getData(url);
console.log(data);
【问题讨论】:
标签: javascript api error-handling async-await fetch-api