...

/

Promises and async-await in Node.js

Promises and async-await in Node.js

Learn the importance of promises and how to handle them using async-await.

What is a promise?

We often make a web request, an API request, or maybe a database request while creating software applications. These operations usually take a millisecond or probably more to get a connection and get the data back. So if we’re going to call it, store the response in a local variable, and try to access the response, we’ll always get into trouble (since the data may not be available instantly).

Then promises come into the picture. These operations usually return a promise, i.e., they say that they “promise” to bring something from the web, database, or any other source, in just a few milliseconds or even seconds, or else say that it failed.

Press + to interact

A promise in JavaScript is just like a promise in real life. What we do is commit to something by saying we promise to do something. For example, we promise to make the best software we can, and then that promise has one of two results: either that promise gets completed (it’s resolved), or that promise fails (it’s rejected). So if we’re able to deliver the best software, then we would resolve our promise; but if we failed to provide the best software, then the promise would be rejected.

How to create a promise

Now let's look at the actual syntax of creating a promise. We’ll follow the steps mentioned below to create a promise:

  1. We start by ...