This question already has answers here:
Why do I need to await an async function when it is not supposedly returning a Promise?
(3 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
This is my first time using promises and mongoose, and I'm trying to save data to global variable for later use
const getUser = async () => {
let user
try {
user = await clientModel.findOne({username: email})
consoe.log(user)
} catch (e) {
console.log(e)
}
return user
}
const filteredUser = getUser().then((value) => {
return value
}).catch((e) => console.log(e));
console.log(filteredUser)
user console log displays content:
{
_id: new ObjectId("61aa75c64e1526131d98f2a1"),
username: 'paul#beatles.uk',
chequing: null,
saving: '1000022',
__v: 0
}
but filteredUser keeps displaying Promise { <pending> }
You need to resolve promise for use data. Read about that here
It can be await or then
Related
This question already has answers here:
async/await implicitly returns promise?
(5 answers)
Why is my asynchronous function returning Promise { <pending> } instead of a value?
(9 answers)
Async function returning promise, instead of value
(3 answers)
How can I access the value of a promise?
(14 answers)
What are asynchronous functions in JavaScript? What is "async" and "await" in JavaScript?
(2 answers)
Closed 19 days ago.
I am trying to fetch data from an endpoint in my project, but continue to get a Promise back instead of the actual data. First of all I should say that I am not getting an error, however I just don't understand why I couldn't handle the returned data from the api call outside of the function.
So I have this function fetchUser that makes a call to the API, and returned the data successfully when I log it to the console. But what I want is to be able to use this data in my JSX. Below is the function call to the API route:
const fetchUser = async () => {
const baseUrl = "/api/user";
const response = await axios.get(baseUrl);
const { data } = response;
const role = data.map((item) => {
const { role } = item;
return role;
});
return role;
};
const userRole = fetchUser().then((result) => {
console.log(result) // returned the data as I expected and wanted (e.g: [Brand])
return result;
});
console.log("Role", userRole); // Returned a 'Promise'(as shown below)
Role:
Promise {<pending>}
[[Prototype]]
Promise
[[PromiseState]]
"fulfilled"
[[PromiseResult]]
Array(1)
Please point me in the right direction to resolve this issue
This happens because of the async nature of the Promise object. What you're storing in the userRole variable is a Promise object.
One way to work this out is either await the response, like this:
// This is my preferable method, as I can avoid nested calls
try {
const userRole = await fetchUser();
console.log(userRole)
}
catch (error) {
console.log(error)
}
The other way is to handle your data inside the .then(), like this:
fetchUser()
.then(res => console.log(res))
.catch(error => console.log(error))
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my asynchronous function returning Promise { <pending> } instead of a value?
(9 answers)
async/await implicitly returns promise?
(5 answers)
Async function returning promise, instead of value
(3 answers)
Closed last year.
I am getting stuck on a Mongoose function. The goal of the function is to:
Store DB query in the query variable
Return True IF there is a DB query matching my criteria. False, otherwise.
The code looks something like:
let query = function (query) {
return new Promise((res, rej) => {
res(UserModel.findOne({ username: toString(query) }));
})
.then((user) => {
return user;
})
.catch((rej) => {
console.log(rej);
});
};
let result = await query(usernameToQuery);
if (result == null) {
return true;
} else {
return false;
}
No matter what I do, this code will never return after the query statement has been resolved. All it ever returns to the calling function is promise <pending>. How would I fix this?
This question already has answers here:
How can I access the value of a promise?
(14 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I'm building backend to fetch pictures of users I follow. The function below is a helper function that takes an array of user IDs to map against it to get their pictures. This function returns a single promise.
const getFeedPhotos = async (followingArr) => {
const promises = followingArr.map(async userId => {
await Photo.find({userId: mongoose.Types.ObjectId(userId)});
});
const x = Promise.all(promises);
return x;
};
Code below is the router itself where I am invoking my helper function.
photoRouter.get(
'/feed',
expressAsyncHandler(async (req, res) => {
const following = req.body.following;
if (following) {
const response = getFeedPhotos(following);
console.log(response);
} else {
res.status(400).send({ message: '"Following" is not provided.' })
}
})
);
The problem is that response equals to Promise { <pending> }. I need this promise to resolve in order to send it to my client. My question is how do I do that? I do realize that it has to do with some blunder of mine and stems from my misunderstanding of the whole async concept per se. I was trying to make some research but none of the solutions worked for me.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How can I access the value of a promise?
(14 answers)
Closed 1 year ago.
I'm trying to write an async function that returns the response from the find ISS API using axios.
What's happening is whatever I ty to return winds up as a pending promise.
If I try to access the information in the function with console.log that works
async function apiCall(url) {
try {
const response = await axios.get(url);
console.log(response.status)
return response;
} catch (error) {
console.error(error);
}
}
console.log(apiCall("http://api.open-notify.org/iss-now.json"))
and it logs
Promise { <pending> } 200
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I am using axios to retrieve data from my BackEnd but the promise is still pending.
I have used .then() even async and await. I am using .then(res => res.data) since i know that every promise has "data" key holding the retrieved data and that after that it will be returned this way. I also binded the function in the constructor!
async getTrackInfo() {
return await axios.get('http://localhost:60231/api/values')
.then(res => res.data);
};
componentDidMount() {
const data = this.getTrackInfo();
console.log(data);
this.setState({
tracks: data
});
}
But unfortunately, it returns undefined.
Following code would work:-
async getTrackInfo() {
return await axios.get('http://localhost:60231/api/values')
.then(res => res.data);
};
async componentDidMount() { // Make this function async
const data = await this.getTrackInfo(); // add await here
console.log(data);
this.setState({
tracks: data
});
}