【问题标题】:How to await a fetch function in a function?如何在函数中等待获取函数?
【发布时间】:2019-04-23 10:28:14
【问题描述】:

下面是我的代码

export const redirectDomain: any = (lang, ctx, res) => {
    let redirectString;

    const getData = async () => {
        try {
            const response = await fetch('https://www.example.com');
            const data= await response.json();

            return data;
        } catch (error) {
            console.log('[ERROR]');
        }
    };

    const data = getData();
    const redirectUrl = data.split(',');

    return redirectUrl;
};

为什么输出会显示错误

无法读取未定义的属性“拆分”

【问题讨论】:

  • 你必须const data = await getData()...虽然我希望错误更像data.split is not a function
  • 你不必等待getData(),因为它是异步的吗?
  • @PatrickRoberts 虽然错误是正确的,但在我的控制台中评估 (undefined).a() 会得到 Uncaught TypeError: Cannot read property 'a' of undefined
  • @DevanshJ 你应该评估的是const data = new Promise(() => {}); data.split()
  • @PatrickRoberts 哦,是的,我的错 xD 你是对的,它说“未捕获的 TypeError:data.split 不是函数”

标签: javascript async-await fetch


【解决方案1】:

async 函数之外的事情不会等待承诺得到解决。因此,当您 split 时,data 仍然是 undefined。所以这是解决方案之一......

export const redirectDomain: any = async (lang, ctx, res) => {
    let redirectString;

    const getData = async () => {
        try {
            const response = await fetch('https://www.example.com');
            const data = await response.json();

            return data;
        } catch (error) {
            console.log('[ERROR]');
        }
    };

    const data = await getData();
    const redirectUrl = data.split(',');

    return redirectUrl;
};

另一种解决方案(我更喜欢这个):

export const redirectDomain: any = async (lang, ctx, res) => {
    let redirectString;
    let data;
    try {
        const response = await fetch('https://www.example.com');
        data = await response.json();
    } catch (error) {
        console.log('[ERROR]');
    }

    const redirectUrl = data.split(',');

    return redirectUrl;
};

另外,如果我要编写这段代码(让我弄清楚我将如何处理错误 xD):

export const redirectDomain: any = (lang, ctx, resp) =>
    fetch("https://www.example.com")
    .then(res => res.json())
    .then(data => Promise.resolve(data.split(",")));

我想说的是,有时 promise 看起来比 async/await 更好。

【讨论】:

    【解决方案2】:

    只需等待getDataredirectDomain 必须是async 才能执行此操作

    -export const redirectDomain: any = (lang, ctx, res) => {
    +export const redirectDomain: any = async (lang, ctx, res) => {
        let redirectString;
    
        const getData = async () => {
            try {
                const response = await fetch('https://www.example.com');
                const data= await response.json();
    
                return data;
            } catch (error) {
                console.log('[ERROR]');
            }
        };
    
    -   const data = getData();
    +   const data = await getData();
        const redirectUrl = data.split(',');
    
        return redirectUrl;
    };
    

    【讨论】:

      【解决方案3】:

      您收到此错误是因为您的数据未定义

      试试axios库,替代fetch

      const resp = axios.get('https://www.example.com');
      

      返回resp.data;

      【讨论】:

        猜你喜欢
        • 2022-07-06
        • 2023-02-07
        • 2021-08-21
        • 2021-09-23
        • 2017-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多