index.js

1.
module.exports = function() {
2.
	var plugin = {};
3.
	var package = require("./package.json");
4.
	var promise = require("./lib/promise");
5.
	
6.
	plugin.name = package["name"];
7.
	plugin.version = package["version"];
8.

			
9.
	plugin.promise = function(func) {
10.
		return new promise(func);
11.
	}
12.

			
13.
	/**
14.
	 * Using this function you can easily promisify a function. Supply the function you want to 
15.
	 * promisify as first argument and when you call the function that is returned from this 
16.
	 * function using the arguments you would have normally used, it'll return a promise. When the 
17.
	 * function is finished it'll resolve the promise, but when the first parameter in the callback
18.
	 * function is an error it'll throw an error.<br>
19.
	 * [Click me](/views/cerus-promise/reference/promise.html) for the documentation about the 
20.
	 * promise class.
21.
	 * @param {Function} func The function to promisify.
22.
	 * @param {Object} (bindings = this) The object to bind to the function call.
23.
	 * @returns {Function} The promisified version of the original function.
24.
	 * @class promisify
25.
	 */
26.
	plugin.promisify = function(func, bindings) {
27.
		if(typeof func !== "function") {
28.
			throw new TypeError("The argument func must be a function");
29.
		}
30.

			
31.
		return (...args) => {
32.
			return new promise(event => {
33.
				func.call(bindings || this, ...args, (err, ...values) => {
34.
					if(err instanceof Error) {
35.
						return event("error", err);
36.
					}
37.
					else if(err !== null) {
38.
						values.unshift(err);
39.
					}
40.

			
41.
					event("success", ...values);
42.
				});
43.
			});
44.
		}
45.
	}
46.

			
47.
	return plugin;
48.
}