Hi there
I have an async function which I would like to convert to an Observable stream (using rxjs operators). The await
calls must execute in the order they appear in the function.
async authenticateUser(profile: Profile): Promise<any> {
let authCookie: any;
try {
authCookie = await getCookie();
} catch (error) {
console.error(error);
}
if (!authCookie || authCookie?.length < 1) {
cancelAuthenticationCookieGet();
throw {message: "login failed", status: -2};
}
await saveProfileAsync(profile);
await storeCurrentAuthCookieAsync(authCookie);
storeSessionStorage();
await setPartitionSessionCookie(profile.url, authCookie);
}
Is there a clean way to accomplish the above?
await undefined;
which does - nothing. You only need to use await
on promises - respectively when a function returns a promise
I'm frustrated after an hour of debugging this, maybe you guys can help. I have a file to interact with my MongoDB, and it has:
exports.getUserDetails = async username => {
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(async err => {
if (err) throw err;
const collection = client.db('db').collection('users');
const result = await collection.findOne({ username });
return result;
});
};
and I call it as:
const details = await dbUtils.getUserDetails(username);
console.log(`got ${ details}`); // prints "got undefined"
await
in my getUserDetails
function I add a console.log
, it prints out the object
app.post('/register', async (req, res) => {
const { error } = schema.validate(req.body);
if (error) {
return res.status(401).json({
status: false,
message: error.details[0].message
});
}
// Check if user is already in DB
const userEmailExist = await User.findOne({ email: req.body.email });
if (userEmailExist) {
return res.status(409).json({
status: false,
message: "Email already exists"
});
}
// Hash user password
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);
// Create new user and save to MongoDB
const user = new User({
name: req.body.name,
email: req.body.email,
emailToken: crypto.randomBytes(64).toString('hex'),
password: hashedPassword
});
const msg = {
to: user.email, // Change to your recipient
from: 'mrkelechichinaka@gmail.com', // Change to your verified sender
subject: 'Account Verification Token',
text: `
Hello, thanks for registering on our site.
Please copy and paste the address below to verify your account.
`,
html: `
<h1>Hello,</h1>
<p>Thanks for registering on our site.</p>
<p>Please click the link below to verify your account.</p>
`
}
try {
await user.save();
await sgMail.send(msg)
res.send(`Email sent successfully to ${user.email}`);
res.redirect('/');
} catch (error) {
console.log(error);
res.send(`Something went wrong. Please contact us noreply@gmail.com`);
res.redirect('/');
}
});
hi guys I kinda need urgent help right now. I have an assignment but currently I have a little challenge with connecting parts. Here is the task
a web app which logs calculations as they happen and shares those calculations with everyone connected to the app.
currently I have implemented a calculator using React and it works perfectly I have also setup a server using node, express and socket.io my current challenge is how to get inputs from the calculator to be displayed in a form of chats which is the socket.io and node setup. Any input is appreciated.
It seems simple enough to put into practice, however I am confused on how the function is being called. Here is the meat of the file.
const asyncUtil = fn =>
function asyncUtilWrap(...args) {
const fnReturn = fn(...args)
const next = args[args.length-1]
return Promise.resolve(fnReturn).catch(next)
}
Here is an example of what its use is
const asyncHandler = require('express-async-handler')
express.get('/', asyncHandler(async (req, res, next) => {
const bar = await foo.findAll();
res.send(bar)
}))
Without express-async-handler
express.get('/',(req, res, next) => {
foo.findAll()
.then ( bar => {
res.send(bar)
} )
.catch(next); // error passed on to the error handling route
})
I don't understand when asyncUtilWrap gets called.
I understand that asyncUtil accepts a function as an argument. In most cases it will be the callback from express. Then in the example we query are databases for all the items. At what point does asuncUtilWrap take over. By the name of it it sounds like it wraps our original function. However I have tried a few console messages within the function and I can't get it to fire off. Any help would be appreciated . Thank you!