Skip to content
This repository has been archived by the owner on May 22, 2021. It is now read-only.

Replace callbacks w/ promise wrappers with util.promisify? #64

Closed
pdehaan opened this issue Jun 8, 2017 · 2 comments
Closed

Replace callbacks w/ promise wrappers with util.promisify? #64

pdehaan opened this issue Jun 8, 2017 · 2 comments

Comments

@pdehaan
Copy link
Contributor

pdehaan commented Jun 8, 2017

In the spirit of needless optimizations, we may be able to reduce the code by a few bytes if we use the new Node 8 util.promisify() in a couple places.

Ref: http://2ality.com/2017/05/util-promisify.html

For example, instead of this:

function filename(id) {
  return new Promise((resolve, reject) => {
    redis_client.hget(id, 'filename', (err, reply) => {
      if (!err) {
        resolve(reply);
      } else {
        reject();
      }
    });
  });
}

... we may be able to shorten to:

const { promisify } = require('util');
// ...

function filename(id) {
  const hget = promisify(redis_client.hget);
  return hget(id, 'filename');
}

And in theory the above will resolve with the reply object or reject with the err object.
I don't think we can use it in all the places we're using wrapper Promise objects though.

@pdehaan
Copy link
Contributor Author

pdehaan commented Jun 8, 2017

Another example:

function localDelete(id, delete_token) {
  return new Promise((resolve, reject) => {
    redis_client.hget(id, 'delete', (err, reply) => {
      if (!reply || delete_token !== reply) {
        reject();
      } else {
        redis_client.del(id);
        resolve(fs.unlinkSync(__dirname + '/../static/' + id));
      }
    });
  });
}

function localForceDelete(id) {
  return new Promise((resolve, reject) => {
    redis_client.del(id);
    resolve(fs.unlinkSync(__dirname + '/../static/' + id));
  });
}

vs

function localDelete(id, delete_token) {
  const hget = promisify(redis_client.hget);
  return hget(id, 'delete')
    .then((reply) => {
      if (!reply || reply !== delete_token) {
        throw new Error(`Uh oh, unable to delete ${id}: ${reply}`);
      }
      return localForceDelete(id);
    });
}

function localForceDelete(id) {
  redis_client.del(id);
  return Promise.resolve(fs.unlinkSync(path.join(__dirname, '..', 'static', id)));
}

@dannycoates dannycoates added this to the Stretch milestone Jun 20, 2017
@pdehaan
Copy link
Contributor Author

pdehaan commented Jun 23, 2017

Potentially better approach (at the expense of yet another dependency): https://github.com/NodeRedis/node_redis#promises

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants