Promises in JavaScript - Interview Question...

promises

Introducing promises

In your day-to-day life, you often promise people something in advance of actually doing it. Perhaps you said, “I promise I will clean the dishes,” or, “I promise I will buy some milk.” This is essentially how promises in JavaScript work. When you use a promise, you are usually writing asynchronous code and you are making a promise or a transaction for something that is going to be done.

Once the promise is done, then the task is either fulfilled or failed. This is like you either fulfilled your promise of buying milk or you forgot so your promise failed.

There are two parts to understand when you are working with promises. Creating the promise and then how to use the promise.

Creating a promise
A promise is a constructor function so you must use the new keyword and a promise becomes Promise when you create one. The promise takes a function as the argument with two parameters: resolve and reject.

Resolve and reject are functions that can be called so they need to be executed with parentheses. Resolve and reject get used to determine what happens when the promise runs. Let’s look at the basic syntax for creating a promise.


        <script>

            const ourPromise = new Promise((resolve, reject) => {
            });
            console.log(ourPromise);

        </script>


In the above example, we use const and declare a variable called ourPromise. Initially, this is uninitialised but then we use the keywords new and Promise (promise is a constructor function). We pass in the resolve and reject parameters.

Promise states
There are three states which promises can have. Pending, fulfilled and rejected. The ourPromise we created does not resolve or reject anything so it will remain indefinitely in the pending state. It’s a bit like someone waiting on you to go out and buy your milk.

To complete a promise, we use resolve or reject. Resolve means that the promise succeeds and reject means it fails. Any argument can be passed into resolve and reject but often when we work with promises we are making data requests so it is an object that you would extract some data from.

Resolving and Rejecting
Let’s update our example to show the outcome of resolving and then rejecting the promise.


        <script>
           
            const ourPromise = new Promise((resolve, reject) => {
            resolve();
            });
            console.log(ourPromise);

        </script>


                <script>

            const ourPromise = new Promise((resolve, reject) => {
            reject();
            });
            console.log(ourPromise);

        </script>

When we resolve our promise the state becomes fulfilled. When we reject it the state becomes rejected. Now we will also update our example so it better represents a request.