I have a question about asynchronous/synchronous when we write code in JS and I have done google search but I am still a bit confused.
I understand that we use callback functions when we want to make sure that the callback function is executed only after the asynchronous task (such as accessing database) in the outer function is complete. I understand how deserialize and serialize user works.
I am confused why when we do serialize user or deserialize user with passport.js
we need a callback function like this ?
passport.serializeUser((user, done) => {
done(null, user.id);
});
If all we want is that the inner arrow function that is passed as an argument to serializeUser()
to be executed only after serializeUser()
is finished. Or why do we need to pass it as a callback function instead of calling that arrow function below serializeUser()
? I thought JS is synchronous so it will execute the arrow function after serializeUser()
is completed anyway ?
I only found serializeUser()
documentation in passport documentation on how to use it, but not its implementation so I am also confused whether serializeUser()
or deserializeUser()
( or any other passport functions) are asynchronous functions ?
Thank you !
serializeUser
will run the callback function whenever it want. You need to pass it as a function because that's howserializeUser
is implemented. You cannot simply run the function "below"serializeUser
because you need the arguments the callback function receives (like, say, the user). See stackoverflow.com/q/27637609/438992. – Dave NewtonserializeUser()
not asynchronous then ? Because we need to use async/await. – bubble rainserializeUser
calls it. It may be at the end of its normal flow, it may not be--all you could do is look at the source to see how/when the callback is used. – Dave Newton