Reputation: 286
I am using react-native, mongo DB and node js and I need to create some database functions and put them in some modules to be able to reuse them whenever I want. To fetch data from the mongo database, I use the fetch()
function which returns a promise. So, for all functions that I created that did not return a value, I used .then
and I faced no problems. On the other side, when I return a value inside a fetch().then()
function and use this returned value, I get undefined. The code I use for the function looks like:
export const getUsers = () => {
//I cannot use this function because of returning a promise
fetch("http://1jjsd12zaws.ngrok.io/database/", {
method: "GET",
headers: {
"Content-Type": "application/json",
},
})
.then((res) => {
res.json();
})
.then((data) => {
return JSON.stringify(data);
});
};
Then, when I try to run this code:
let users=getUsers();
console.log(users);
It prints undefined
.
What I think is going on is that the console.log(users)
runs before getUsers()
returns its value. But I do not know why does this happen and I want it to wait for getUsers()
to execute then, completes its work.
Upvotes: 0
Views: 2581
Reputation: 5657
fetch(..)
inside getUsers
(that's why you are getting undefined
)res.json()
inside the first then
getUsers
returns a Promise, then you need to use .then
(or async/await
) to access the promise value: getUsers().then(users => {...})
const getUsers = () => {
return fetch('http://1jjsd12zaws.ngrok.io/database/', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
return res.json();
})
.then(data => {
return JSON.stringify(data);
});
};
getUsers().then(users => console.log(users))
Upvotes: 3
Reputation: 1
Async and await should cover it. The example on MDN docs explains it better than I can and should apply to your use case.
Upvotes: 0