In conjunction with the callbacks, it would be nice if session.save() returned a promise as well. This would make in-lining session operations with if blocks, try/catch blocks and loops a lot more straightforward since async/await could be used.
For example, I'm running into race conditions with redirecting happening too soon. So in situations where I need to set the session, like a "flash" message, I have to do this:
try {
// some error prone operation
} catch(err) {
flash('error', 'something went wrong')
}
req.session.save((err) => {
res.redirect('/things')
})
You'll notice session.save() is called regardless of whether the error occurs. I'm choosing to do that instead of duplicate the res.redirect() code into multiple places.
However, what I'd rather have is:
try {
// some error prone operation
} catch(err) {
flash('error', 'something went wrong')
await req.session.save()
}
res.redirect('/things')
in the meantime could you do something like:
try {
// some error prone operation
} catch(err) {
flash('error', 'something went wrong')
await new Promise((resolve,reject) =>{
req.session.save((err)=>{
resolve();
})
})
}
res.redirect('/things')
It'd be nice to have promises returned elsewhere where callbacks are used as well, e.g., destroy.
There are 2 ways:
Many popular libraries follow the second way, e.g. fs-extra or ioredis, so they support both callback and promise APIs. And now as I see this is returned from all session methods. So, perhaps, the second way is better.
@dougwilson
If I create a pull request with this feature, will you accept it? And what way to choose?
i wish promise applied!! :)
@RussCoder No matter what, the operation is async so a return value of anything other than a promise seems kind of pointless. I've seen it done where returning a promise AND calling the callback are possible if supplied.
Most helpful comment
There are 2 ways:
Many popular libraries follow the second way, e.g.
fs-extraorioredis, so they support both callback and promise APIs. And now as I seethisis returned from all session methods. So, perhaps, the second way is better.@dougwilson
If I create a pull request with this feature, will you accept it? And what way to choose?