Skip to content

Instantly share code, notes, and snippets.

@MarkTiedemann
Created November 29, 2015 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarkTiedemann/d4b8a2c4c7b6ae7ac57e to your computer and use it in GitHub Desktop.
Save MarkTiedemann/d4b8a2c4c7b6ae7ac57e to your computer and use it in GitHub Desktop.
Promisifying A Callback-based Function In Node 5

Promisifying A Callback-based Function In Node 5

Node 5 is awesome! <3 By default, it comes with lots of ES6 features.

Among them are, for example, arrow functions. And there's the spread operator which, in combination with the arguments object, makes writing a promisify() function beautifully simple:

function promisify (foo) {
  return function () {
    return new Promise ((resolve, reject) => {
      foo(...arguments, (error, result) => {
        if (error) reject(error)
        else resolve(result)
      })
    })
  }
}

! The function in line 2 can't be replaced with an arrow function. That is because an arrow function does not bind its own arguments object.

And the best part of this, with ES7, soon you'll be able to await your Promises in async functions! <3

! With Babel, you can already use next generation Node today.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment