Garmaine Staff asked 1 year ago

I have multiple scenarios where, based on a condition, I need to do asynchronous processing and later proceed regardless of the path taken. This code works as I expect:

  let processingComplete = new Promise(function (resolve, reject) { }); // create pending promise
  let condition = true; 

  var wait = function () {
    return new Promise((resolve, reject) => {
      setTimeout(resolve, 500);
    });
  }

  if (condition) {
    processingComplete = wait();
  } else {
    // do something else, synchronously  
    processingComplete = Promise.resolve();
  }

  processingComplete.then(() => {
    console.log("entering processingComplete.then...")
  });

However, if the promises are nested more than one deep the .then clause never fires. For example,

  let processingComplete = new Promise(function (resolve, reject) { }); // create pending promise
  let condition = true; 

  var wait = function () {
    return new Promise((resolve, reject) => {
      setTimeout(resolve, 500);
    });
  }

  if (condition) {
    wait()
    .then(() => {
      processingComplete = wait() // nesting of promises
    })
  } else {
    // do something else, synchronously 
    processingComplete = Promise.resolve();
  }

  processingComplete.then(() => {
    // this code never fires with nested promises
    console.log("entering processingComplete.then...")
  });

I'm certainly familiar with using promises, but I'm not understanding why this does't work. I'd welcome any insights.