DEV Community

Cover image for Node.JS: Asynchronous Functions
Samanta Fluture
Samanta Fluture

Posted on

Node.JS: Asynchronous Functions

When working on projects with Node.JS, we need at some point to use asynchronous functions, especially when it comes to data input and output (I/O - Input/Output). And for that we can use promises, but they can make our code complex and verbose, so we can use async and await and make our code simpler and more beautiful, and that's what we're going to see in this article.

Synchronous and asynchronous processing?

We need to understand these two concepts: synchronous processing is the one that happens in sequence and order, following a queue, and the other asynchronous processing only starts after the current one is completed. This happens in browsers that load files and resources in an orderly fashion, where one load only starts after the other has been completed.

Asynchronous processing is when processes are executed at the same time, with nothing preventing another process from starting while the one that was started previously ends. So a process can start even if another is running. This happens a lot when sending messages or emails, we can send a message, but it hasn't even arrived at the destination and even then we can already create and send another message.

Node.JS uses asynchronous processing, and this can be quite difficult to understand if we compare it to another language like PHP for example. We could use the following code to do a SELECT, INSERT, UPDATE, or anything else in the database:

$result = $connection->query('SELECT * FROM table_name');

echo $result ;

<rest of the code...>
Enter fullscreen mode Exit fullscreen mode

This way the “rest of the code” will only be executed after the SELECT on the table is performed, in Node.JS we need to use something like:

connection.query('SELECT * FROM table_name', function (error, results) {
    console.log(results);
});

<rest of the code...>
Enter fullscreen mode Exit fullscreen mode

The “rest of the code” would be executed soon, “before” the SELECT completed, but we always need to close the connection when the processing is done. But when will it end? We don't know, so we have a problem!

Using promises (promises)

We can use promises (promises, in free translation). In other words: we are going to make a promise that at some point will be fulfilled and we will have a return, or we will be able to do something when it is completed.

Assuming our database connection already returns a promise, we could do something like:

connection.query('SELECT * FROM table_name').then(rows=> {
    console.log(results);
});

<rest of the code...>
Enter fullscreen mode Exit fullscreen mode

And using promises would be easy to solve our problem of closing the connection when the SELECT completes, we can simply chain another then, like so:

connection.query('SELECT * FROM table_name').then(rows=> {
    console.log(results);
}).then(rows => connection.close());

<rest of the code...>
Enter fullscreen mode Exit fullscreen mode

If we need to chain several promises in a row, we will have a problem reading the code and understanding how this processing will actually be.

Improving code with async and await

To solve this other problem, we can use async and await that is present in Node.JS since version 7.6. With it we can make our code simple and easy to understand.

If we have the idea that the code must be easily understood, this may not be so simple using promises, but asynchronous functions make this task easier, as it will work as in PHP, for example, the “rest of the code” will only be executed when the SELECT has been completed.

We can have the following code:

async list() {
const result= await connection.query('SELECT * FROM table_name');

<rest of the code...>
};
Enter fullscreen mode Exit fullscreen mode

Ready! We use an asynchronous function ( async), and inside it the “rest of the code” will only be executed when connection.query('SELECT * FROM table_name') finishes, that is, the result variable will receive the result that is “waiting” ( await) of the SELECT in the database.

Conclusion

Simple, fast! Using async and await makes usability, writing and reading easy to understand. It's so cool that when we start using async and await we hardly ever want to use promises again.

Top comments (0)