I am trying to return an array via axios call from an async function in node js. The axios call works correctly, and console.log shows me the array I am looking for in the data object of the returned promise. But when I use console.log to see the result of the function outside the function, it shows "undefined".
async function userImport (settings, file) {
let usersFile;
const auth = {
"username": settings.authentication.user,
"password": settings.authentication.password
};
const options = {
method: 'get',
headers: {
},
timeout: 10000
};
await axios.get(settings.url,auth,options)
.then((results) => {
usersFile = results.data;
console.log(usersFile);
if (usersFile && usersFile != "" && usersFile != undefined) {
console.log("Test1");
return [usersFile,settings.encoding];
} else {
console.log("Test2");
return results;
}
})
}
await userImport(settings, file)
.then(async (users)=>{
console.log(users);
})
The result I'm getting is:
[{...},{...},{...}] //The array I'm looking for
Test1
Undefined
What I expected to get is:
[{...},{...},{...}] //The array I'm looking for
Test1
[{...},{...},{...}] //The array I'm looking for
I tried putting the array into a json object like this:
let usersFile = {};
usersFile.users = results.data;
then I get:
{users:[{...},{...},{...}]} //The array I'm looking for
Test1
Undefined
I also tried returning results.data directly without putting it in an element, but the results were the same.
If anyone has this issue, I finally figured it out. The issue is with the use of
.then((results)
Because I am calling another function, the "return" was sent for it instead of the outer function, so the outer one finished without a "return".
There were two solutions to this issue:
(the one I picked) change the structure to not use .then in the following way:
usersFile = await axios.get(settings.url,auth,options); usersFile = usersFile.data;
Add another return with the results of the inner function.