1

I have a function that returns a Promise that calls another promise, and has logic that requires both the function argument and the return value of the Promise. I've tried three different approaches:

I can create a new Promise, call another promise inside the promise, and then resolve() my created promise:

function somePromise(functionInput) {
    return new Promise(function(resolve, reject) {
        anotherPromise().then(function (promiseInput) {
            // do something async with promiseInput and functionInput
            // .. resolve(foo);
        });
    });
}

Problem: The logic seems backwards -- I'm really calling anotherPromise() first and talking something on after it resolves, but the return new Promise is the first line. Slight callback hell.

Alternatively, I can return the promise I need to call, and then chain a promise factory to it, and resolve that promise:

function somePromise(functionInput) {
    return anotherPromise().then(function (promiseInput) {
        return new Promise(function(resolve, reject) {
            // do something async with promiseInput and functionInput
            // .. resolve(foo);
        });
    });
}

Problem: There are two return statements, which are definitely confusing. Slight callback hell.

Finally, I can of course break it out into a function 'factory'... that has a promise factory:

function somePromise(functionInput) {
    return anotherPromise().then(doSomething(functionInput));
}

function doSomething(functionInput) {
    return function(promiseInput) {
        return new Promise(function(resolve, reject) {
            // do something async with functionInput and promiseInput
            // .. resolve(foo);
        });
    });
}

Problem: We moved the callback hell to another function, have three returns, and have a Promise-factory function-factory.

It seems none of these approaches are ideal. How can I structure a promise wanting an earlier value, with minimal drawbacks?

apscience
  • 7,033
  • 11
  • 55
  • 89
  • 1
    A pretty good description of your various options here: http://stackoverflow.com/questions/28714298/bluebird-chain-promises – jfriend00 Dec 07 '15 at 08:22

0 Answers0