如何在函数中等待提取函数?

时间:2019-04-22 17:57:54

标签: javascript async-await fetch

下面是我的代码

@search = LocationIqApi.new(YOUR_API_KEY_HERE).find_coordinates(params[:q])

为什么输出将显示错误

  

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

3 个答案:

答案 0 :(得分:2)

async函数之外的内容不会等待诺言得到解决。因此,data undefined仍然是split。所以这是解决方案之一...

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(",")));

我想指出的一点是,有时候承诺看起来比异步/等待更好。

答案 1 :(得分:1)

只需等待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;
};

答案 2 :(得分:0)

由于未定义数据而收到此错误

尝试axios库,替代提取

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

返回相应的数据;