Async/await, Promises and .map() [duplicate] - javascript

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.

Related

Is there another way to get data from an API endpoint or resolve this returned data? [duplicate]

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))

use a function inside another function in the same file with Node Javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 months ago.
I would have a simple question but can't figure it out the answer with Node.JS. Here it is : I got a file with multiple function and I would like to use the return of the first inside the second :
//The first function
const Function1 = (req, res) => {
var axios = require('axios');
var config = {
method: 'get',
url: 'xxxxx.json',
headers: {
//...
}
};
axios(config).then(function(response) {
const array = response.data.datas
return Promise.all(Object.values(array).map(entry => {
return entry.id
}))
}).then(function(response) {
//I got an array with infos
return response
}).catch(function(error) {
console.log(error);
});
}
const Function2 = (req, res) => {
const previousResult = function1()
//Undefined
console.log(previousResult)
}
How should I proceed ?
Thanks a lot
Do you need to call the function?
function1()
Update:
It looks like you added to your question. This now seems to be an issue with async functions. You should look up how to use promises, and async await. It's a bit too complex to describe here, and there are a lot of tutorials about it. The short answer is that when you return inside of a promise, it doesn't return from the outer function1. You could probably test this in your code by putting an explicit return at the end of function1 and you'll see that in console.log().

async/await display data in global scope [duplicate]

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

node js, function returning undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
so I have a function (getBagId) that I want to return the bag id, I know its not returning it due to the async nature, but how would i go about fixing it so it returns the bagId, heres the code
const getBagId = () => {
request.get('https://www.off---white.com/en-us/api/users/me', options, (err, res, data) => {
bagId = data.bagId
})
return bagId
}
once again I want the function to return bagId so the value is set to that, also i want to do this only using callbacks, no promises or async await, thanks
Use request-promise
const getBagId = async () => {
const response = await rp({ uri : 'https://www.off---white.com/en-us/api/users/me' })
// Process the `bagId` from the response (JSON / XML / ??? )
const bagId = // `bagId` from response.
return bagId
}
You could make use of promises:
const getBagId = () => {
return new Promise((res, rej) => {
request.get('https://www.off---white.com/en-us/api/users/me', options, (err, res, data) => {
if(err) return rej(err);
return res(data.bagId);
});
});
}
But now your .getBagId() returns a promise, so you'll have to handle it accordingly in your application
request.get is an asynchronous function, so getById needs to return a promise or to execute asynchronously by using async/await. Otherwise you cannot do it unless there is some version of request.get method that execute synchronously, which I highly doubt that it exists.

Returning Promise { <pending> } for object value [duplicate]

This question already has answers here:
Why is my asynchronous function returning Promise { <pending> } instead of a value?
(9 answers)
Closed 3 years ago.
I'm building a blog and for each blog post I'm trying to include the authors name, rather than the authors ID.
I have two functions: getUserName and mapData.
mapData remaps the blog object:
function mapData(posts) {
let result = [];
result = posts.map(post => ({
id: post._id,
title: post.title,
imageURL: post.imageURL,
body: post.body,
author: getUserName(post.createdBy),
date: date(post.createdAt)
}));
console.log(result)
return result;
}
getUserName gets the users name:
const getUserName = async id => {
try {
const getUser = await User.findById(id)
console.log(getUser)
return getUser.firstname;
} catch (err) {
throw err;
}
}
But after console logging the result in mapData the value for author is Promise { <pending> }. Can anyone explain why this is happening? I thought by using an async function would avoid this?
An async function returns a Promise. The easiest thing to do here would be to mark the map cb as async as well and then await getUserName();
As mentioned in the comments this can get a bit messy because you'd be dealing with many more Promises afterwards. If you'd rather not deal with that and you're using MongooseJS you could use Populate, for the author field which will simply return the data you need with only one call on your part.

Categories

Resources