How to correctly chain conditional(?) promises with Q.js <p>I've still not quite got a complete understanding of promises so apologies if this is a simple misunderstanding.</p> <p>I have a function for deleting an item on a page but I have a specific behaviour depending on the state of the page. Psuedo code-wise it's something like this:</p> <pre><code>Does the page have changes? If yes - prompt to save changes first If yes - save changes If no - exit function If no - continue Prompt to confirm delete If yes - delete item and reload data If no - exit function </code></pre> <p>Hopefully that makes sense. Essentially if there are changes, the data must be saved first. Then if the data has been saved, or if there were no changes to begin with, prompt the user to confirm deletion. The problem is I'm using durandal and breeze, and I can't seem to chain the promises they return together correctly.</p> <p>My function currently looks like this, which I know is wrong, but I'm struggling to work out where to fix it.</p> <pre><code>if (this.hasChanges()) { app.showMessage('Changes must be saved before removing external accounts. Would you like to save your changes now?', 'Unsaved Changes...', ['Yes', 'No']) .then(function (selectedOption) { if (selectedOption === 'Yes') { return this.save(); } else { Q.resolve() } }); } app.showMessage('Are you sure you want to delete this item?', 'Delete?', ['Yes', 'No']) .then(function (selectedOption) { if (selectedOption === 'Yes') { item.entityAspect.setDeleted(); datacontext.saveChanges() .then(function () { logger.logNotificationInfo('Item deleted.', '', router.activeInstruction().config.moduleId); Q.resolve(this.refresh(true)); }.bind(this)); } }.bind(this)); </code></pre> <p>The app.showMessage call from durandal returns a promise, then the this.save returns a promise, and finally the this.refresh also returns a promise.</p> <p>So I guess I need to check the hasChanges, then if necessary call save, and resolve it. Then after that conditional section has finished resolving, call the second prompt, and then resolve all the promises within that.</p> <p>I'm sorry I don't think this is super clear, but that's also I think coming from the fact I'm not completely following the chains here.</p> <p>Any help much appreciated! Thanks.</p>