如何返回从 API Javascript 解析自定义数据的承诺
因此,我正在使用国家气象服务创建天气应用程序。但是获取的数据非常复杂,我需要获取两个不同的API。因此,我想编写一个自定义的异步函数,该函数返回承诺,该函数解决了仅包含我需要的必要数据的对象。
我想到了这样的事情:
async function fetchWeatherAPI(){
//data that I need
let data = {};
try {
const res1 = await fetch(url1);
const result1 = await res1.json();
data = {...data , result1.usefulData};
} catch(error){}
try {
const res2 = await fetch(url2);
const result2 = await res2.json();
data = {...data, result2.usefulData};
} catch(error){}
return new Promise((resolve,reject)=>{
resolve(data);
})
}
此代码对我有用。但是问题是,如果API拒绝该怎么办?如何处理错误,以便可以在返回的承诺中显示错误消息?我可能想要这样的东西:
return new Promise((resolve,reject)=>{
if(...) reject(errrorMessage);
resolve(data);
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需
返回数据
。您已经在async
函数中,该函数的返回值将是async
函数已经返回的承诺的解析值:此外,您的
捕获
块正在默默地吃字,并试图继续努力,好像什么都没有错。您可能只希望该错误传播回呼叫者,因此,如果您只需删除try/catch
块,那就是这样。而且,您拥有的
返回新的Promise()
是完全多余的和不必要的(称为反模式)。您可以将其删除,然后返回数据
。注意:由于您显示的代码没有显示您的第一个和第二个
fetch()
调用之间的任何依赖性,因此您可以并行运行它们,也许更快地完成它们。或者,在执行大量
fetch()
调用时,我经常在代码中使用助手功能:Just do
return data
. You're already inside anasync
function and the return value from that function will be the resolved value of the promise that theasync
function already returns:In addition, your
catch
blocks are silently eating errors and attempting to continue as if nothing went wrong. You probably just want the error to propagate back to the caller so if you just remove yourtry/catch
blocks, that's what will happen.And, the
return new Promise()
you have is entirely superfluous and unnecessary (referred to as an anti-pattern). You can just remove it andreturn data
instead.Note: Since the code you show does not show any dependency between your first and second
fetch()
calls, you could run them in parallel and perhaps finish them faster.Or, I often use a helper function in my code when doing a lot of
fetch()
calls: