Skip to content

Instantly share code, notes, and snippets.

@jmerrifield
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmerrifield/233cba5fb0446fa24698 to your computer and use it in GitHub Desktop.
Save jmerrifield/233cba5fb0446fa24698 to your computer and use it in GitHub Desktop.
Using promises to delay an action until arbitrary async preconditions are met.
var when = require('when')
// An array of promises that must resolve before we can submit
var preSubmitActions = []
function loadSomeScript() {
// An example use case. We want to delay the submit until
// some script has loaded. We start loading the script in postRender
// so it may or may not be finished by the time someone clicks submit
preSubmitActions.push(when($.getScript('http://example.org/some-script.js')))
}
function submitButtonClick() {
// Disable button so it can't be clicked again
// Show some 'loading' text
when.all(preSubmitActions)
.then(function () {
// Perform the **actual** submit action here
// Optionally return a promise to benefit from consolidated
// error handling
})
.otherwise(function (err) {
// Gets invoked if any of the pre-submit actions fail
// or the `.then` handler fails, so a nice place to
// consolidate error-handling for all steps of the submit.
// Re-enable button
// Hide 'loading' text
// Show error message
})
.ensure(function () {
// This gets called regardless of the outcome, if the
// action is repeatable (rather than something final
// which causes the page to redirect) then you might
// like to re-enable the submit button here instead.
})
}

An example of how we could use an array of promises to delay form submission until an arbitrary set of async preconditions complete. Useful for

  • Kicking off a script load when we show the view, which may or may not be complete by the time the submit button is clicked.
  • Background uploading of an image which should finish before the submit action can be performed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment