如何返回从 API Javascript 解析自定义数据的承诺

发布于 2025-01-18 16:43:12 字数 939 浏览 3 评论 0 原文

因此,我正在使用国家气象服务创建天气应用程序。但是获取的数据非常复杂,我需要获取两个不同的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);
})

So I'm using the API of National Weather Service to create a weather app. But the fetched data is very complicated, and I need to fetch two different APIs. So I want to write a customized async function that returns a promise, which resolves to an object that contains only the necessary data I need.

I came up with something like this:

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);
    })

}

This code is working for me. But the problem is, what if the APIs reject? How can I handle the error so that I can display the error message in the returned promise? I may want something like this:

return new Promise((resolve,reject)=>{
    if(...) reject(errrorMessage); 
    resolve(data);
})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小镇女孩 2025-01-25 16:43:12

只需返回数据。您已经在 async 函数中,该函数的返回值将是 async 函数已经返回的承诺的解析值:

async function fetchWeatherAPI(){
    //data that I need
    let data = {};
    
    const res1 = await fetch(url1);
    const result1 = await res1.json();
    data = {...data , result1.usefulData};

    const res2 = await fetch(url2);
    const result2 = await res2.json();
    data = {...data, result2.usefulData};
    return data;
}

此外,您的捕获块正在默默地吃字,并试图继续努力,好像什么都没有错。您可能只希望该错误传播回呼叫者,因此,如果您只需删除 try/catch 块,那就是这样。

而且,您拥有的返回新的Promise()是完全多余的和不必要的(称为反模式)。您可以将其删除,然后返回数据


注意:由于您显示的代码没有显示您的第一个和第二个 fetch()调用之间的任何依赖性,因此您可以并行运行它们,也许更快地完成它们。

async function fetchWeatherAPI(){
    //data that I need
    let data = {};

    const [result1, result2] = await Promise.all([
        fetch(url1).then(r => r.json()),
        fetch(url2).then(r => r.json())
    ]);

    return {...data, result1.usefulData, result2.usefulData};
}

或者,在执行大量 fetch()调用时,我经常在代码中使用助手功能:

function fetchJson(...args) {
    return fetch(...args).then(r => r.json());
}

async function fetchWeatherAPI() {
    //data that I need
    let data = {};

    const [result1, result2] = await Promise.all([
        fetchJson(url1),
        fetchJson(url2)
    ]);

    return { ...data, result1.usefulData, result2.usefulData };
}

Just do return data. You're already inside an async function and the return value from that function will be the resolved value of the promise that the async function already returns:

async function fetchWeatherAPI(){
    //data that I need
    let data = {};
    
    const res1 = await fetch(url1);
    const result1 = await res1.json();
    data = {...data , result1.usefulData};

    const res2 = await fetch(url2);
    const result2 = await res2.json();
    data = {...data, result2.usefulData};
    return data;
}

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 your try/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 and return 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.

async function fetchWeatherAPI(){
    //data that I need
    let data = {};

    const [result1, result2] = await Promise.all([
        fetch(url1).then(r => r.json()),
        fetch(url2).then(r => r.json())
    ]);

    return {...data, result1.usefulData, result2.usefulData};
}

Or, I often use a helper function in my code when doing a lot of fetch() calls:

function fetchJson(...args) {
    return fetch(...args).then(r => r.json());
}

async function fetchWeatherAPI() {
    //data that I need
    let data = {};

    const [result1, result2] = await Promise.all([
        fetchJson(url1),
        fetchJson(url2)
    ]);

    return { ...data, result1.usefulData, result2.usefulData };
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文