Skip to content

Instantly share code, notes, and snippets.

@ianb
Last active December 15, 2015 19:29
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 ianb/5312213 to your computer and use it in GitHub Desktop.
Save ianb/5312213 to your computer and use it in GitHub Desktop.
function promisize(func) {
return function () {
try {
var promise = func.apply(this, arguments);
if (! promise.isThenable) {
var result = new Resolver();
result.resolve(promise);
return result.promise;
} else {
return promise;
}
} catch (e) {
var result = new Resolver();
result.reject(e);
return result.promise;
}
};
}
// Usage:
SomeObect.prototype.method = promisizer(function (arg) {
if (typeof arg != "string") {
throw "Bad argument";
}
if (arg in this._cache) {
return this._cache[arg];
}
var data = loadFromStorage();
var result = new Resolver();
result.then(
function (data) {result.resolve(munge(data));},
result.reject.bind(result));
return result.promise;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment