Promise Me
Promise Me helps you move your code from using callbacks to using promises, for example through Q, RSVP.js or when.js.
It parses your code and then manipulates the AST to transform the callbacks into calls to then()
, including a rejection handler if you handle the original callback error. Think of it as a slightly smarter find-and-replace. It will probably break your code and require you to fix it.
Try the live demo!
Installation and usage
$ npm install -g promise-me$ promise-me script.js
API
var promiseMe = ; var before = "...";var after = promiseMe;
promiseMe.convert(code, options)
Convert the given code to use promises.
{string} code
String containing Javascript code.{Object} options
Options for generation.{Object} options.parse
Options foresprima.parse
. See http://esprima.org/doc/ .{Object} options.generate
Options forescodegen.generate
. See https://github.com/Constellation/escodegen/wiki/API .{Function} options.matcher
A function of form(node) => boolean
. Must accept any type of node and return true if it should be transformed intothen
, using the replacer, and false if not. See https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API for node types.{Function} options.replacer
A function of form(node) => Node
. Must accept any type of node and return a new node to replace it that usesthen
instead of a callback. Will only get called if options.matcher returns true. See https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API for node types.{Function} options.flattener
A function of form(node) => Node
. Must accept any type of node, and return either return the original node, or a new node with thethen
calls flattened.{Function} log
Function to call with log messages.- Returns
{string}
The Javascript code with callbacks replaced with.then()
functions.
Examples
Simple callback
Before:
;
After:
;
Error handling
Before:
;
After:
;
Nested callbacks
Before:
;
After:
;
Captured variables
Before:
;
After:
;