Monday, October 2, 2017

NodeJS/Javascript callback

This article will show you the simple callback example.

Firstly, you have a task

[gist https://gist.github.com/vanduc1102/7e3ece4d85fe7265406e61dfa54b337c]

Result:

asyncDoTask.js2017-10-02 12-56-12

The code is very simple, each line of code is executed line by line the result is predicted. But life is not that easy because NodeJS and Javascript are single thread

For the I/O tasks like make AJAX requests, read a file or saving user profile to database it will take a little of time to get the task done

We will have this kind of code:
[gist https://gist.github.com/vanduc1102/540c1bd3a22ad26d83889456b3bc9cfa]

Result:

asyncDoTask.js2017-10-02 12-56-50

Oop! The result is out of control.

Now callback will help you.

[gist https://gist.github.com/vanduc1102/5e2e7cea325e628ad91fa11f6170d7a1]

asyncDoTask.js2017-10-02 12-57-16

That is the very first sight about callback.

1 comment:

  1. […] The last article with the callback, we use callback function to solve the issue with asynchronous in Nodejs/Javascript. […]

    ReplyDelete