Promise.method(function(...arguments) fn) -> function
Returns a new function that wraps the given function fn
. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function.
This method is convenient when a function can sometimes return synchronously or throw synchronously.
Example without using Promise.method
:
MyClass.prototype.method = function(input) { if (!this.isValid(input)) { return Promise.reject(new TypeError("input is not valid")); } if (this.cache(input)) { return Promise.resolve(this.someCachedValue); } return db.queryAsync(input).bind(this).then(function(value) { this.someCachedValue = value; return value; }); };
Using the same function Promise.method
, there is no need to manually wrap direct return or throw values into a promise:
MyClass.prototype.method = Promise.method(function(input) { if (!this.isValid(input)) { throw new TypeError("input is not valid"); } if (this.cache(input)) { return this.someCachedValue; } return db.queryAsync(input).bind(this).then(function(value) { this.someCachedValue = value; return value; }); });
© 2013–2018 Petka Antonov
Licensed under the MIT License.
http://bluebirdjs.com/docs/api/promise.method.html