snippetjavascriptMinor
Create a person if no duplicate exists
Viewed 0 times
duplicatepersoncreateexists
Problem
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.
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.
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.
Solution
To me it looks like you should move the
Then you can rewrite the code as:
You could also look at the Bluebird promise library
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
Code Snippets
function handleError(e( {
console.log(e.stack);
return self.createOdsPerson()
.then(self.addAsParticipant.bind(self, redirect));
}self.getPotentialPersonDuplicates()
.then(promptUserToPickFromDuplicatePersons)
.then(selectPersonFromDuplicatePersonLookup)
.then(addAsParticipant )
.catch(handleError)
.then($ui.stopWaiting);Context
StackExchange Code Review Q#158671, answer score: 5
Revisions (0)
No revisions yet.