Daryl Daryl - 1 month ago 4x
jQuery Question

How to Trigger Two Promises and Conditionally Wait For One?

For example: I'm on a "create new account" page for a website. Before creating the account, I need to determine if the e-mail that is given is a junk e-mail (i.e. test@test.com). I also need to determine if the account already exists, returning back a list of possible accounts that should be used instead of the new one (maybe the address already exists, etc.) These are defined as such:

function emailIsValid(): JQueryPromise<boolean> { ... }
function getPotentialDuplicates(): JQueryPromise<IDupResults> { ... }

Hypothetically, let's say the
call has to check a really old database that's super slow, taking 3-5 seconds to finish, while the
usually takes .4 seconds. Therefore, I'd like to kick both of these calls off simultaneously with this results being defined by this action tree:

  • If -
    returns first:

    • Wait for
      to return

    • If - email is valid:

      1. If - no dups are found, Create Account

      2. Else - show dups to user.

    • Else - Ignore dupResults and display "Email is Invalid"

  • Else -
    returns First:

    • If - email is valid:

      1. Wait for

      2. If - no dups are found, Create Account

      3. Else - show dups to user.

    • Else - Don't wait for
      and display "Email is Invalid"

Currently I'm using
but this waits for both to finish. Is there a simple way of defining this?


In both your cases you want to wait for emailIsValid. So :

// kick off both
const emailIsValidProm = emailIsValid();
const getPotentialDuplicatesProm = getPotentialDuplicates();

emailIsValidProm.then((res)=> {
     if (res.invalid) { // if res in valid
     else {
       // now wait for the other 
       return getPotentialDuplicatesProm
.then(res=> {
   if (!res) return; // email wasn't valid;
   // The res is for `getPotentialDuplicatesProm
   // USE it !

PS: highly recommend not using Jquery promises and using standard Promise api. I have docs on the standard one : https://basarat.gitbooks.io/typescript/content/docs/promise.html