Example:
attempt(function () {
JSON.parse();
}).
fail(function (e) {
console.error(e);
});| 'use strict'; | |
| function attempt(fn) { | |
| return Object.create({ | |
| 'fail': function (onError) { | |
| try { | |
| fn(); | |
| } | |
| catch (e) { | |
| return onError(e); | |
| } | |
| } | |
| }); | |
| } | |
| exports = module.exports = attempt; |
A few confusing bits as a consumer:
function fallable() {
// Do work.
callback(null, JSON.parse(/* data from closure? */));
}
attempt(fallable).fail(callback);Either way, I think it's worth trying out if it helps inlining.
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: