Message from JavaScript discussions

September 2020

— Why is it setting headers even before the async task completion?

— 

Let len = 0;
listUsersResult.users.forEach(async (userRecord) => {
userRecord.toJSON();
let uid = userRecord.toJSON().uid;
let mUser = await User.findOne({ uid })
.populate("role", ["title"])
.lean();
if (mUser) len++;
mUser.photoUrl = userRecord.photoURL;
mUser.email = userRecord.email;
mUser.name = userRecord.displayName;
users.push(mUser);
if (len === listUsersResult.users.length) {
return res.status(200).json({ users });
}
});

— Did it with a terrible way.

— Come on dude

— Wt should I do then?

— Suggest smthng better.

— What is userRecord?

— Router.get("/users", async (req, res) => {
try {
let users = [];
listAllUsers();
async function listAllUsers(nextPageToken) {
var listUsersResult = await admin.auth().listUsers(1000, nextPageToken);
if (!listUsersResult)
return res.status(404).json({ msg: "No user found!" });

let len = 0;
listUsersResult.users.forEach(async (userRecord) => {
userRecord.toJSON();
let uid = userRecord.toJSON().uid;
let mUser = await User.findOne({ uid })
.populate("role", ["title"])
.lean();
if (mUser) len++;
mUser.photoUrl = userRecord.photoURL;
mUser.email = userRecord.email;
mUser.name = userRecord.displayName;
users.push(mUser);
if (len === listUsersResult.users.length) {
return res.status(200).json({ users });
}
});
if (listUsersResult.pageToken) listAllUsers(listUsersResult.pageToken);
}
} catch (err) {
console.log(err.message);
return res.status(500).json({ msg: err.message });
}
});

Message permanent page

— Coming from the firebase

— Why do you need to fetch mUser first?

— Why not just run an update query?

— User.findOneAndUpdate is a thing