Promises have two callback functions, each reporting the state of the promise. Resolve is called when the promise is successful, and reject is called when it fails. The parameters passed to these two functions are accessible to the function via .then() and .catch() as shown below.
For example, given an array of shapes “shapes”, and an array of arrays containing integers “values” of the dimensions of the relative shape, we are asked to return an array of the areas of the shapes, or [-1] if a shape isn’t found. For simplicity, we will only allow two shapes. (1) Square. (2) Rectangle
Our calculate area function will look like this…
Works as expected, we can use this function to calculate all multiple areas as our example instructed. Let’s see what our getAreas function can look like…
This implementation may seem accurate at first sight, but it is not. It will NOT return [-1] as expected if a wrong shape is provided with a set of correct shapes. Given a triangle, the expected output is [-1] but it fails.
Remember, promises do not wait and execute linearly, thus the parent promise will resolve with areas_array containing the areas of the correct shapes. This is a good example of a place one would need to wait for a promise to resolve or reject before proceeding.
We have already covered how to make use of promises through async…await. So let’s update our function to wait for calculateShape to return each time before proceeding.
On Line 21 we added async and on Line 26 we added await. Our getAreas function will now return the expected output for an array of shapes and array of values. See below for expected test outputs.
Don’t wait for that promise to resolve.