nodejs – asynchronous explained

nodejs – asynchronous explained

In this article i will talk about asynchronous nodejs functions. I use express as the routing middleware and pug as the template engine. The code below shows the setup for the nodejs snippets used later on in this post:

We have setup the nodejs app with the code above. Now we are going to add the routes that we want to publish in our example app, see the code below:

When we navigate to ‘http://localhost:3000’ the route ‘/’ is processed. This will render our index.pug file which has the following contents:

Pressing the ‘Sign up’ button will take us to the ‘http://localhost:3000/read’ route. As you can see this route will try to read the ‘./test.txt’ file, The fs.readFile is an asynchronous function. When the readFile operation is complete it will execute the callback that is provided as the second parameter.

When an error occurs fs.readFile will execute the callback with an error object (the data parameter will be ‘undefined’). The error object contains, as you expect, a description of the error:

If you would like to have a complete stacktrace in your error object you should change the line ‘next(err)’ to next(new Error(err)’, the resulting error after this change:

The code above makes use of the callback function of the readFile method on the fs object. An alternative way of accomplishing the same result is to use promises. Lets have a look at the code below:

As you can see we wrap our fs.readFile in a Promise object. A promise will be rejected on error (the file could not be found for example) and will be resolved on success. When a promise is rejected the catch code block will be executed. If the promise is resolved the then code block will be executed.

The advantage of using a promise is that we can wait on the result if we want to. The code below will wait for the readFile function to complete and then continues the /read handle after the wait promise line


Leave a Reply

Your email address will not be published. Required fields are marked *