How to Pass a Variable Into a Callback Function in Node.js
Because Node.js works asynchronously, things might not work as you think, if you are still stuck in the synchronous world..
To pass variables into callback function, you can use bind()
.
I will show you how.
The dummy function that takes 1 sec to callback
To begin, let’s say we have this dummy()
function that will do some lengthy processing, and then callback. This is common. For example, a simple http request will use a callback function for the http response.
1 2 3 4 5 6 7 |
|
Incorrect Code
Now, let’s have a code that loops 10 times.
1 2 3 4 5 6 |
|
You might think the code above will print out i
as 1-10.
But wrongly, it will print 10 every time!
This is because the callback from dummy()
takes 1 second before calling back. So by the time we print out, i
is already 10.
Correct Code
There is the correct way to pass variables such as i
into the callback function.
1 2 3 4 5 6 |
|
As you can see, I have used bind()
to pass the variables to function(response)
.
Then in the callback, I can access the variable with this.i
.