Running the promise example in Terminal

Now that we have a very basic promise example in place, let's run it from the Terminal using nodemon, which we installed in the previous chapter. We'll add nodemon, and then we'll go into the playground folder, /promise.js:

When we do this right away, our app runs and we get success. Hey. It worked! This happens instantaneously. There was no delay because we haven't done anything asynchronously. Now when we first explored callbacks (refer to Chapter 5, Basics of Asynchronous Programming in Node.js ), we used setTimeout to simulate a delay, and this is exactly what we'll do in this case.

Inside our somePromise function, we'll call setTimeout, passing in the two arguments: the function to call after the delay and the delay in milliseconds. I'll go with 2500, which is 2.5 seconds:

var somePromise = new Promise((resolve, reject) => {
setTimeout(() => {

}, 2500);

Now after those 2.5 seconds are up, then, and only then, do we want to resolve the promise. This means that our function, the one we pass into then will not get called for 2.5 seconds. Because, as we know, this will not get called until the promise resolves. I'll save the file, which will restart nodemon:

In Terminal, you can see we have our delay, and then success: Hey it worked! prints to the screen. This 2.5 second delay was caused by this setTimeout. After the delay was up (in this case it's an artificial delay, but later it'll be a real delay), we're able to resolve with the data.