Last active
December 15, 2015 19:29
-
-
Save ianb/5312213 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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