Chapter 14: Promises, needed async and awaits

I was able to complete the coffeerun exercise (except for the ch14 silver challenge,) however it did require adding async and await keywords to the .then returning functions, all the way up to the original calling function.

For example, in one of the challenges of an earlier chapter, the reader was given the exercise of detecting if an order was placed already, to deny an additional order by that same email at the same time.

After the promises were added in ch14, my solution to extract the boolean of the presence of an order from a promise included the following function in the truck.js file:

  Truck.prototype.doesHaveOrder = async function (customerId) {
    console.log('Check for order for ' + customerId);
    return await this.db.get(customerId)
      .then(
        (order) => {
          return order != null && typeof order != 'undefined';
        }
      );
  }

This was being called starting from within Formhandler addInputHandler’s input event handler function, so I added the async keyword, there:

FormHandler.prototype.addInputHandler = function (
    fnIsCompanyEmail
    , fnDoesHaveOrder
  ) {
    console.log('Setting input handler for form');
    this.$formElement.on('input', '[name="emailAddress"]', async function (event) {

and the await later, where I wanted the final output value of the promise unwrapped by the .then call above:

      var emailAddress = event.target.value;
      var message = '';
      if (await fnDoesHaveOrder(emailAddress)) {
        message = emailAddress + ' already has an order placed!'
        event.target.setCustomValidity(message);
      } else if (fnIsCompanyEmail(emailAddress)) {

Since there were two other functions separating the two above, I needed to place async and awaits in each of those, as well.

In main.js:

  formHandler.addInputHandler(
    Validation.isCompanyEmail
    , async function (emailAddress) {
        return await Validation.isUsedEmail(emailAddress)
      }
  );

and in validation.js

isUsedEmail: async function (email) {
  return await myTruck.doesHaveOrder(email);
},

I’m not sure if this is the correct way to resolve the issue, but otherwise I hope this helps anyone who is stuck (like I was) wondering how to get a return value out of a Promise.