UNPKG

1.13 kBJavaScriptView Raw
1'use strict'
2
3/**
4 * promiseOrCallback will convert a function that returns a promise
5 * into one that will either make a node-style callback or return a promise
6 * based on whether or not a callback is passed in.
7 *
8 * @example
9 * prompt('input? ').then(function (input) {
10 * // deal with input
11 * })
12 * var prompt2 = promiseOrCallback(prompt)
13 * prompt('input? ', function (err, input) {
14 * // deal with input
15 * })
16 *
17 * @param {Function} fn a promise returning function to wrap
18 * @returns {Function} a function that behaves like before unless called with a callback
19 */
20function promiseOrCallback (fn) {
21 return function () {
22 if (typeof arguments[arguments.length - 1] === 'function') {
23 let args = Array.prototype.slice.call(arguments)
24 let callback = args.pop()
25 fn.apply(null, args).then(function () {
26 let args = Array.prototype.slice.call(arguments)
27 args.unshift(null)
28 callback.apply(null, args)
29 }).catch(function (err) {
30 callback(err)
31 })
32 } else {
33 return fn.apply(null, arguments)
34 }
35 }
36}
37
38exports.promiseOrCallback = promiseOrCallback