Skip to content

Instantly share code, notes, and snippets.

@tlivings
Last active December 27, 2015 15:39
Show Gist options
  • Select an option

  • Save tlivings/7349274 to your computer and use it in GitHub Desktop.

Select an option

Save tlivings/7349274 to your computer and use it in GitHub Desktop.
Try catch utility so optimization still occurs in the calling function. lol?
'use strict';
function attempt(fn) {
return Object.create({
'fail': function (onError) {
try {
fn();
}
catch (e) {
return onError(e);
}
}
});
}
exports = module.exports = attempt;

Example:

attempt(function () {
    JSON.parse();
}).
fail(function (e) {
    console.error(e);
});
@totherik
Copy link
Copy Markdown

totherik commented Nov 7, 2013

Creating new objects, closures, and functions are unlikely to be faster, especially since the try/catch will prevent them from being inlined. First, a refactor:

function attempt(fn) {
    return {
        fail: function (reject) {
            try {
                fn();
            catch (err) {
                reject(err);
            }
        }
    }
}

@totherik
Copy link
Copy Markdown

totherik commented Nov 7, 2013

A few confusing bits as a consumer:

  1. You have to invoke fail to execute the intended behavior. Could be moot or obvious, just interesting side-effect.
  2. The consumer needs to wrap the intended behavior in order to reconcile both callbacks/"re-join" the result:
function fallable() {
    // Do work.
    callback(null, JSON.parse(/* data from closure? */));
}

attempt(fallable).fail(callback);

@totherik
Copy link
Copy Markdown

totherik commented Nov 7, 2013

Either way, I think it's worth trying out if it helps inlining.

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