Reputation: 518
I am trying to update the array list for user in the userList
... to have a property called valid if userDetails.length
is not zero.
But the userList never gets updated.
userList.map(async function(user) {
let userId = user.id
await db.queryUser(userId)
.then(function(userDetails){
if(userDetails.length !== 0){
user.valid = true;
}
});
});
I tried doing this:
let filteredList = userList.map(async function(user) {
let userId = user.id
await db.queryUser(userId)
.then(function(userDetails){
if(userDetails.length !== 0){
user.valid = true;
}
});
});
but the promise stays pending. Any better way to this?
UPDATE
Got it to work using the following code:
await Promise.all(userList.map(async function(user) {
let userId = user.id
await db.queryUser(userId)
.then(function(userDetails){
if(userDetails.length !== 0){
user.valid = true;
}
});
})
)
Upvotes: 0
Views: 74
Reputation: 7614
The promises are pending because you never await for them. You are just creating a map of promises.
If you want to update the users in place, you don't need a map for that:
for (let user of userList) {
const userDetails = await db.queryUser(user.id);
if (userDetauls.length) user.valid = true;
}
(assuming the outer function is async, otherwise use .then
instead of await
)
UPDATE Well, this will, however, execute the queries in a serial manner. Maybe you want them to run in parallel.
In that case, you may want to actually do the map, but then await the promises using Promise.all
.
Something like this: await Promise.all(userList.map(...));
Upvotes: 0
Reputation: 1
Well, it looks like you are trying to use async/await syntax with the .then syntax instead of in place of it. Try storing the response into the variable userDetails when you call your queryUser function then do your check on the length like so:
let filteredList = userList.map(async function(user) {
let userId = user.id
let userDetails = await db.queryUser(userId)
if(userDetails.length !== 0){
user.valid = true;
}
});
Upvotes: 0