Async Function returning Undefined when calling it - javascript

I'm Having some trouble with this function on a React project
let fetchData = async (event, imagen) => {
const apiURL = `https://some_api_call/${imagen}`;
await axios.get(apiURL).then((response) => {
console.log(response.data.Imagen1.data);
return response.data.Imagen1.data;
});
When i call it the Console.log returns Undefined but the console log above returns the data
fetchData(event, rowData.Codigo).then(function (response) {
console.log(response);
});

let fetchData = async (event, imagen) => {
const apiURL = `https://some_api_call/${imagen}`;
return await axios.get(apiURL);
}
fetchData(event, rowData.Codigo).then(function (response) {
console.log(response);
});

Your fetchData function has no return statement. You probably don't want to use then when there is await:
async function fetchData(event, imagen) {
const apiURL = `https://some_api_call/${imagen}`;
const response = await axios.get(apiURL)
console.log(response.data.Imagen1.data);
return response.data.Imagen1.data;
}

Related

JS, use of Async Await function in Axios when mapping over an array

The function is intended to loop over an array and POST each value in the array to database. I got error if I use async await function.
Error : Can not use keyword 'await' outside an async function
const myfunction = async () => {
[1,2,3].map((item) => {
const endpoint = "/api/";
await apiService(endpoint, "POST", item)
.then((r) => console.log(r))
});
};
The apiservice function use browser fetch function with stored cookie
This might be duplicate of following question Using async await when mapping over an arrays values, but I did not understand it.
The reason is that await does not occur directly in your async function, but in a function that is passed to .map (which is not async).
Besides, .map is abused here, since you do not return anything in the callback, nor use the array that .map returns.
Just use a for loop instead:
const myfunction = async () => {
for (let item of [1,2,3]) {
const endpoint = "/api/";
await apiService(endpoint, "POST", item)
.then((r) => console.log(r))
}
}
Also, using then is an antipattern here, since await is actually there to avoid using that. So better code it like this:
const myfunction = async () => {
for (let item of [1,2,3]) {
const endpoint = "/api/";
let r = await apiService(endpoint, "POST", item)
console.log(r);
}
}
const myfunction = () => {
[1,2,3].map( async(item) => { // async should be here
const endpoint = "/api/";
await apiService(endpoint, "POST", item)
.then((r) => console.log(r))
});
};
This should work
const myfunction = () => {
[1,2,3].map(async (item) => {
const endpoint = "/api/";
await apiService(endpoint, "POST", item)
.then((r) => console.log(r))
});
};

React JS - promise returns before execution completes. Async function does not work

I am trying to load data from firebase by calling a function in which it filters data and returns them.
When I call this function in my main function, it returns "undefined". I know the data is there (console.log(postsArray)) prints the data but I guess the return executes before data is loaded.
What am I doing wrong?
calling_Function_in_Main = async () => {
const data = await FirebaseData ();
console.log(data);
};
FirebaseData is the function that I call in my main function to load data and to return them
let postsArrays=[];
const FirebaseData = async () => {
const getViewableLink = async (link) => { //some function };
const loadData = async () => {
const database = firebase.database();
const data = database.ref();
const loadProfile = data
.child('Posts')
.orderByChild('Active')
.equalTo(true)
.once('value', function gotData(data) {
Object.values(readInfo).forEach(async (element) => {
element.Option1Link = await getViewableLink(
preLink + element.Option1Link,
);
postsArray.push(element);
}
});
})
.catch((error) => {
console.log(error);
}
})
.then((postsArray) => {
console.log(postsArray);
return postsArray;
});
};
await loadData();
};
export default FirebaseSwipeData;
You can't use foreach with async/await because It is not asynchronous. It is blocking.
you have 2 ways to fix this:
1- Reading in sequence: you can use for...of loop
for(const element of Object.values(readInfo)) {
element.Option1Link = await getViewableLink(
preLink + element.Option1Link,
);
postsArray.push(element);
}
2- Reading in parallel: you can use Promise.all
await Promise.all(Object.values(readInfo).map(async (element) => {
element.Option1Link = await getViewableLink(
preLink + element.Option1Link,
);
postsArray.push(element);
}));
Hope that solves the problem, for you

What is the correct way to export an Async function module?

I have a file asyncAwait.js that has a simple function:
async function doStuff() {
return(`Function returned string.`);
}
module.exports.doStuff = doStuff;
In another module, testing.js, I invoke and all works as expected:
var functions = require(`./functions`);
(async () => {
const test = await functions.asyncAwait.doStuff();
console.log(test);
})();
This logs "Function returned string." to the console.
All good.
However, if I use axios in asyncAwait.js:
const axios = require(`axios`);
async function doStuff(parameter) {
const url = `https://jsonplaceholder.typicode.com/posts/1`;
const getData = async url => {
try {
const response = await axios.get(url);
const data = response.data;
console.log(data);
} catch (error) {
console.log(error);
}
};
return(getData(url));
}
module.exports.doStuff = doStuff;
Then in testing.js:
var functions = require(`./functions`);
(async () => {
const test = await functions.asyncAwait.doStuff();
console.log(test);
})();
This logs undefined.
Why does the function call return undefined in the second example?
In your example getData has no return. In this case your function will implicitly return undefined. To fix it you could change that function to the following:
const getData = async url => {
try {
const response = await axios.get(url);
return response.data;
} catch (error) {
return error
}
};
module.exports.doStuff = doStuff;
May I suggest you :
module.exports=doStuff;
Or
exports.doStuff
and maybe but not sure what you're trying to achieve
replace
return(getData(url));
by
return(()=>{return getData(url)});

How to save returned value to variable with async/await using axios?

So i have the following example:
const userApi = async () => {
const res = await axios({
url: URL + "getUserData",
method: "post",
data: { message: "getUserList" }
});
return res.data;
};
some_other_function = () => {
const userList = [];
userList = userApi().then(res => {
// console.log(res) works here but i need to get the response data outside...
return res;
});
console.log(userList); // It's still a promise... Why?
};
I can't get the response object into a variable, the promise doesn't resolve no matter what. How should i do this?
userApi().then(res => {
userList = res //also doesn't work
return res
})
console.log(userList)
You are trying to access a variable from within your function scope outside of the function. Try this instead and let me know if it worked.
const userApi = async () => {
const res = await axios({
url: URL + 'getUserData',
method: 'post',
data: {message: 'getUserList'}
})
return res.data
};
let userList = [];
some_other_function = async () => {
userList = await userApi();
}
This should do it.
const userList = await userApi();
console.log(userList);
some_other_function = async () => {
const userList = await userApi()
console.log(userList)
}

struggle to wrap promise with async await

I got unexpected identifier but not sure what is the mistake. I'm using fetch which is already a promise.
async getUsers = () => {
const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
return resp
}
getUsers().then(users => console.log(users))
Notice the position of the async keyword:
Not:
async getUsers = () => {
But:
getUsers = async () => {
Run:
getUsers = async () => {
const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
return resp;
};
getUsers().then(users => console.log(users))
As per comments:
Should I chain then() in getUsers()? async/await suppose to eliminate then() am I right?
Yes, you can await any Promise. Or use both .then() sometimes and await at others (like does the code above). But you could just use async/await as well.
The example below uses no .then():
getUsers = async () => {
const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1')
return resp.json();
};
(async () => {
// notice to use the await keyword, the code must be wrapped in an async function
const users = await getUsers();
console.log(users);
})();
Aside from the typo in the async word pointed by #acdcjunior, you're mixing async / await with the usual promise handling (.then()) which is not wrong but kind of defeats the point. Using only async / await would look like:
const getUsers = async () => {
const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1');
return resp.json();
}
async function fetchUsers() {
try {
const users = await getUsers();
console.log(users);
} catch(err) {
console.log(err);
}
}
fetchUsers();
you have the syntax wrong:
const getusers = async () => {
...
}
const is optional
Your syntax of declaring your function is wrong, here's some explanation.
If getUsers is a method of a react component class the syntax should be :
getUsers = async () => {
const resp = await fetch(
'https://jsonplaceholder.typicode.com/posts/1'
).then(response => response.json());
return resp;
};
or :
async getUsers() {
const resp = await fetch(
'https://jsonplaceholder.typicode.com/posts/1'
).then(response => response.json());
return resp;
};
If it's outside of a react component class or in a stateless arrow function component you can use this syntax :
const getUsers = async () => {
const resp = await fetch(
'https://jsonplaceholder.typicode.com/posts/1'
).then(response => response.json());
return resp;
};
const getUsers = async () => {
try {
const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1');
return resp.json();
} catch(e) {
console.error(e)
}
}
(async () => {
const users = await getUsers();
console.log(users)
})()
Use this, and run

Categories

Resources