4
\$\begingroup\$

I am new to promises and although I am enjoying the simplicity after dealing with callback hell I am having some issues trying to chain them together as you can see by the mess below. So basically what I am trying to achieve is to run through the chain and if there are no duplicate people found then hit the catch and create the person. If not then go down the chain through the subsequent promises and it works but i feel like i am going about this in the wrong manner. I think it is because in each promise i am resolve to true or false.

self.getPotentialPersonDuplicates()
    .then(function (result) {
        return result.length > 0
            ? self.promptUserToPickFromDuplicatePersons(result)
            : Promise.reject(new Error("There where no duplicates found"));
    })
    .then(function (result) { return result ? self.selectPersonFromDuplicatePersonLookup() : Promise.resolve(); })
    .then(function (result) { return result ? self.addAsParticipant(redirect) : Promise.resolve(); })
    .catch(function (e) {
        console.log(e.stack);
        return self.createOdsPerson()
        .then(self.addAsParticipant.bind(self, redirect));
    })
    .then($ui.stopWaiting());

The promise methods in there contain a lot of code and I don't think there are any code review related issues so I have not included them.

\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

To me it looks like you should move the if (result) into each one of promptUserToPickFromDuplicatePersons, selectPersonFromDuplicatePersonLookup and addAsParticipant and add a method:

function handleError(e( {
    console.log(e.stack);
    return self.createOdsPerson()
           .then(self.addAsParticipant.bind(self, redirect));
}

Then you can rewrite the code as:

self.getPotentialPersonDuplicates()
  .then(promptUserToPickFromDuplicatePersons)
  .then(selectPersonFromDuplicatePersonLookup)
  .then(addAsParticipant )
  .catch(handleError)
  .then($ui.stopWaiting);

You could also look at the Bluebird promise library

\$\endgroup\$
2
  • \$\begingroup\$ I am already using Bluebird, is there a better solution for bluebird? Thanks mark I will try this and out \$\endgroup\$ Commented Mar 24, 2017 at 9:24
  • \$\begingroup\$ It worked a charm thanks. The only difference was I had to bind the this context but that just JS issue ha \$\endgroup\$ Commented Mar 24, 2017 at 10:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.