Practice JavaScript Promises with Hotdog / Not Hotdog

Hotdog / Not Hotdog

Now that you’ve gone through the details of the Promise API, let’s practice what you’ve learned with an exercise.

In this exercise, you’ll create an app that can analyze a photo, and let you know whether it is a hotdog, or… not a hotdog (as shown in HBO’s Silicon Valley series).

To start you off, I’ve provided a few functions that return data asynchronously:

  • fetchModel() downloads a tensor flow model for use with isHotdog(), and returns a promise to the model.

  • fetchImage(url, callback) downloads an image from the specified URL, creating a JavaScript Image object and passing it to the supplied callback. You can supply any URL that the browser has access to. I’ve started you off with the URL for a hotdog in the editor below.

    It doesn’t return anything immediately, but instead calls the supplied callback when the download is complete, or when an error has occured. The callback is expected to follow the legacy callback convention:

    • If an error occurs, it will be provided as the callback’s first argument, i.e. callback(error) will be called.
    • If the download is completed successfully, the result will be provided as the second argument, i.e. callback(null, model) will be called.
  • isHotdog(photo, model) takes an Image and a Model object, and returns a promise to a boolean that indicates whether the image is a hotdog.

I’ve also provided some helpers for working with the data returned by the API:

  • renderImage(image) displays the supplied image in the UI.
  • renderResult(isHotdog) displays “Hotdog!” or “Not Hotdog.” in the UI depending on the supplied boolean.
  • renderError(error) displays the suplied error in the UI.
  • setSimulatedErrorProbability(probability) accepts a number between 0 and 1, and sets the probability that the asynchronous functions will result in an error.

Your task is to retrieve a photo and neural net object with fetchImage() and fetchModel(), then decide whether the received photo is of a hotdog, using isHotdog().

You should display the received photo as soon as it is available, regardless of whether the other two functions complete successfully. You should also make sure to display any errors that occur.

You can test your error handling code by changing the argument to the setSimulatedErrorProbability() function to 0.5 or 1.

If the small editor feels a little crowded, you can put it into fullscreen mode with the button at the top right. And if you do get stuck, remember that you can always take a look at my solution by cliking the “solution” tab at the bottom of the editor. Good luck!

Note: fetchModel() downloads a 2mb model. That’s why it needs to be async!

index.js
api.js
ui.js
index.html
Build In Progress

Thanks to José M. Moreno for creating the not-hotdog project, from which the model in this example was taken.

Progress to next section.