gpt4 book ai didi

javascript - 如何等待函数中的获取函数?

转载 作者:行者123 更新时间:2023-11-30 11:05:32 25 4
gpt4 key购买 nike

下面是我的代码

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

为什么输出会显示错误

Cannot read property 'split' of undefined

最佳答案

async 函数之外的事情不会等待 promise 得到解决。因此,当您拆分时,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(",")));

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

关于javascript - 如何等待函数中的获取函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55798797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com