Things outside the async function won't wait for the promise to get resolved. And hence data is still undefined when you split it. So here's one of the solutions...
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;
};
Another solution (I would prefer this):
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;
};
Also if I were to write this piece of code (let me figure out how I would handle the error xD):
export const redirectDomain: any = (lang, ctx, resp) =>
fetch("https://www.example.com")
.then(res => res.json())
.then(data => Promise.resolve(data.split(",")));
The point I wanted to make is sometimes promises look better than async/await.
const data = await getData()... though I would expect the error to be something more likedata.split is not a functiongetData()as it is async?(undefined).a()in my console givesUncaught TypeError: Cannot read property 'a' of undefinedconst data = new Promise(() => {}); data.split().