0

I currently have the following promise wrapping function:

var promiseWrap = (promiseInstance, resolveFunc, rejectFunc) => {
    return new Promise((resolvePath, rejectPath) => {
            promiseInstance
                .then((...args) => {
                    resolvePath(resolveFunc.apply(null, args))
                })
                .catch((...args) => {
                    rejectPath(rejectFunc.apply(null, args))
                })
        });
    }

While this works, I get the feeling that it isn't the most efficient way of achieving the desired result, and may even betray a fundamental lack of understanding of how promises work. So this is fairly generic, but how would you refactor this code? Is there even a better way of achieving the same result?

winstonS
  • 63
  • 6
  • 3
    Better ask on [codereview.se] – Tushar Mar 04 '16 at 03:11
  • 2
    I can't see anything gained by creating `promiseWrap`. It seems redundant with promises natural API. – zzzzBov Mar 04 '16 at 03:14
  • 1
    (a) Ask on [Code Review](http://codereview.stackexchange.com/), (b) You can't rely on people correctly guessing your "desired result" from the code, therefore clearly state it. – Roamer-1888 Mar 04 '16 at 04:30

1 Answers1

1

I'm not sure whether you just implemented the Promise constructor antipattern by accident, and are now trying to generalise it, or genuinely recognised the usefulness of functors/monads (congrats!), but you've reinvented the .then method.

Your code is more or less exactly equivalent to

function promiseWrap(promiseInstance, resolveFunc, rejectFunc) {
    // assuming promiseInstance instanceof Promise - if not, add a `Promise.resolve()`
    return promiseInstance.then(resolveFunc, rejectFunc);
}

Indeed, this return value of then() calls - another promise for the result of the callback(s) - is what promises are all about.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375