Async functions do not return correct values
# Problem
This library exposes many async functions that swallow any returned data or errors from redis if you try to use them as a promise instead of a callback function. These functions should return data and errors in the fashion of a promise as well.
### Functions in Question
- get: [./index.ts#L99](https://github.com/tj/connect-redis/blob/master/index.ts#L99)
- set: [./index.ts#L110](https://github.com/tj/connect-redis/blob/master/index.ts#L110)
- touch: [./index.ts#L127](https://github.com/tj/connect-redis/blob/master/index.ts#L127)
- destroy: [./index.ts#L138](https://github.com/tj/connect-redis/blob/master/index.ts#L138)
- clear: [./index.ts#L148](https://github.com/tj/connect-redis/blob/master/index.ts#L148)
- length: [./index.ts#L159](https://github.com/tj/connect-redis/blob/master/index.ts#L159)
- ids: [./index.ts#L168](https://github.com/tj/connect-redis/blob/master/index.ts#L168)
- all: [./index.ts#L181](https://github.com/tj/connect-redis/blob/master/index.ts#L181)
## Proposed Solution
Just make the callback function optional. If it's present, have it behave as it does right now. If it's not, let it behave as a promise. That way both callbacks and promises work as expected without breaking existing behaviors.
Just make a helper function to wrap cbs with:
```javascript
function optionalCb(err: unknown, data: unknown, cb: Function) {
if (cb) return cb(err, data)
if (err) throw err
return data
}
```
And this is how you would use it
E.g. the get function
```javascript
async get(sid: string, cb?: Function) {
let key = this.prefix + sid
try {
let data = await this.client.get(key)
if (!data) return optionalCb(null, null, cb)
return optionalCb(null, await this.serializer.parse(data), cb)
} catch (err) {
return optionalCb(err, null, cb)
}
}
```
The helper function is literally a drop in replacement for where you normally call `cb()` so it should be a pretty minor change.
关闭于 2025-05-09 5 条评论