3 /* global module, require */
4 module.exports = function () {
8 // Get a promise object. This may be native, or it may be polyfilled
10 var ES6Promise = require("./promise.js");
13 * thatLooksLikeAPromiseToMe()
15 * Duck-types a promise.
18 * @return {bool} True if this resembles a promise
20 function thatLooksLikeAPromiseToMe(o) {
21 return o && typeof o.then === "function" && typeof o.catch === "function";
27 * Transforms callback-based function -- func(arg1, arg2 .. argN, callback) -- into
28 * an ES6-compatible Promise. Promisify provides a default callback of the form (error, result)
29 * and rejects when `error` is truthy. You can also supply settings object as the second argument.
31 * @param {function} original - The function to promisify
32 * @param {object} settings - Settings object
33 * @param {object} settings.thisArg - A `this` context to use. If not set, assume `settings` _is_ `thisArg`
34 * @param {bool} settings.multiArgs - Should multiple arguments be returned as an array?
35 * @return {function} A promisified version of `original`
37 return function promisify(original, settings) {
40 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
41 args[_key] = arguments[_key];
44 var returnMultipleArguments = settings && settings.multiArgs;
47 if (settings && settings.thisArg) {
48 target = settings.thisArg;
49 } else if (settings) {
53 // Return the promisified function
54 return new ES6Promise(function (resolve, reject) {
56 // Append the callback bound to the context
57 args.push(function callback(err) {
63 for (var _len2 = arguments.length, values = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
64 values[_key2 - 1] = arguments[_key2];
67 if (false === !!returnMultipleArguments) {
68 return resolve(values[0]);
75 var response = original.apply(target, args);
77 // If it looks like original already returns a promise,
78 // then just resolve with that promise. Hopefully, the callback function we added will just be ignored.
79 if (thatLooksLikeAPromiseToMe(response)) {