Nodejs Callbacks Simple Example

nodeJs callbacks simple example

var myCallback = function(data) {
console.log('got data: '+data);
};

var usingItNow = function(callback) {
callback('get it?');
};

Now open node or browser console and paste the above definitions.

Finally use it with this next line:

usingItNow(myCallback);

With Respect to the Node-Style Error Conventions

Costa asked what this would look like if we were to honor the node error callback conventions.

In this convention, the callback should expect to receive at least one argument, the first argument, as an error. Optionally we will have one or more additional arguments, depending on the context. In this case, the context is our above example.

Here I rewrite our example in this convention.

var myCallback = function(err, data) {
if (err) throw err; // Check for the error and throw if it exists.
console.log('got data: '+data); // Otherwise proceed as usual.
};

var usingItNow = function(callback) {
callback(null, 'get it?'); // I dont want to throw an error, so I pass null for the error argument
};

If we want to simulate an error case, we can define usingItNow like this

var usingItNow = function(callback) {
var myError = new Error('My custom error!');
callback(myError, 'get it?'); // I send my error as the first argument.
};

The final usage is exactly the same as in above:

usingItNow(myCallback);

The only difference in behavior would be contingent on which version of usingItNow you've defined: the one that feeds a "truthy value" (an Error object) to the callback for the first argument, or the one that feeds it null for the error argument.

Simple nodejs callback example with fs.readFile

You have several issues going on and I'll try to outline them all as best as possible

Problem 1: Variable scope

var fs = require('fs');
var pathToFile = process.argv[2];

function counter(callback) {
var buffer = fs.readFile(pathToFile, function (err, data) {
// Both of the following variables are scoped to the callback of fs.readFile
var bufferString = buffer.toString();
var bufferStringSplit = bufferString.split('\n');
});
callback();
}

function logMyNumber() {
// Because the variables are in a closure above, bufferStringSplit is null here
console.log(bufferStringSplit.length-1);
}

counter(logMyNumber);

Solution:

Declare the variables in the module's scope:

var fs = require('fs');
var pathToFile = process.argv[2];

// These can now be accessed from anywhere within the module
var bufferString, bufferStringSplit;

function counter(callback) {
fs.readFile(pathToFile, function (err, data) {
bufferString = data.toString();
bufferStringSplit = bufferString.split('\n');
callback();
});
}

// bufferStringSplit should no longer return null here
function logMyNumber() {
console.log(bufferStringSplit.length-1);
}

Problem 2: Callbacks

function counter(callback) {
fs.readFile(pathToFile, function (err, data) {
bufferString = buffer.toString();
bufferStringSplit = bufferString.split('\n');

// Place the callback WITHIN the other callback, otherwise they run in parallel
callback();
});
}

Problem 3: fs.readFile API

fs.readFile doesn't return anything, so your buffer variable below is null

function counter(callback) {      
var buffer = fs.readFile(pathToFile, function (err, data) {
bufferString = buffer.toString();
bufferStringSplit = bufferString.split('\n');
});
callback();
}

Solution:

function counter(callback) {      
fs.readFile(pathToFile, function (err, data) {
// The data argument of the fs.readFile callback is the data buffer
bufferString = data.toString();
bufferStringSplit = bufferString.split('\n');
});
callback();
}

Finally, the code should look like:

var fs = require('fs');
var pathToFile = process.argv[2];

var bufferString, bufferStringSplit;

function counter(callback) {
fs.readFile(pathToFile, function (err, data) {
bufferString = data.toString();
bufferStringSplit = bufferString.split('\n');
callback();
});
}

function logMyNumber() {
console.log(bufferStringSplit.length-1);
}

counter(logMyNumber);

Understanding Callbacks

Imagine get implemented more or less like

function get(url, callback) {
var response = they somehow retrieve the response;
var body = they somehow parse the body;
var error = ...;

// they call you back using your callback
callback( error, response, body );
}

How these values are computed is irrelevant (this is their actual job) but then they just call you back assuming your function actually accepts three arguments in given order (if not you just get a runtime error).

In this sense they also kind of "accept" your callback by ... well, calling it back :) There is no worry about the number of arguments as Javascript is very "forgiving" - methods can be called with any number of arguments, including less or more arguments than the function expects.

Take this as an example:

// they provide 3 arguments
function get( callback ) {
callback( 0, 1, 2 );
}

// but you seem to expect none
get( function() {
});

The get assumes that the callback accepts three arguments while I pass a method that supposedly doesn't accept less arguments. This works, although the three arguments, 0, 1 and 2 are not bound to any formal callback arguments (you can't directly refer to them), they are there in the arguments object, an array-like structure:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

Take another example

function get( callback ) {
callback( 0, 1, 2 );
}

get( function(a,b,c,d,e) {
});

This time the callback I pass seems to expect more arguments than the caller provides and still, no problem here. Arguments are bound to consecutive call parameters, a will get 0, b will get 1, c will get 2 and d and e will get undefined inside the callback body.

Both examples show that the caller doesn't really care how your callback is defined, whether its number of arguments matches the expectation or not. In case of any mismatch, the worst what could happen is a runtime error:

function get( callback ) {
callback( 0, 1, 2 );
}

get( 1 );

// Uncaught TypeError: callback is not a function

How are callback functions executed in node.js?

Does app.listen() return a value to server variable before it executes the callback function?

Yes, exactly. app.listen() resembles to the plain Node.js server.listen method.
The callback is an shortcut for assigning the server an listener to the listening event.

You could do the same with the following code:

var server = app.listen( 3000 );
server.on( "listening", function () {
console.log( "server is listening in port 3000" );
});

How can it do that and how does it work? Is this the same for all callback functions in node (and javascript)?

This happens because IO events in Node.js are all run asynchronously (with exceptions from the fs module) - this is, they will only take place when other synchronous code have finished to run.

This works the same in browser JS - if you run some JS process synchronously, any events triggered (like click, blur, etc) will only execute after that one finishes.

Giving a provided Node JS callback my own custom Callback

you can't quite do what you are doing, you are doing callCount(null, null, printCount) which executes the function. But you need to pass a function as a callback. What you want is something like the following, which captures the call back you want and returns a function you can pass as a callback to your api call

 var callCount = function(callback) {
return function(err, list) {
var count = 0;
if(err) throw err;
// console.log(err);
for (var i = 0; i < list.length; i++) {
// console.log(reqs.path.extname(list[i]));
if(reqs.path.extname(list[i]) === ".png" || reqs.path.extname(list[i]) === ".jpg")
{
count++;
console.log(count);
}
}
callback(count);
}
}

and then

reqs.fs.readdir(dirName, callCount(printCount));

Callback function example

When you pass a function as an argument, it is known as a callback function, and when you return a value through this callback function, the value is a parameter of the passed function.

function myFunction(val, callback){
if(val == 1){
callback(true);
}else{
callback(false);
}
}

myFunction(0,
//the true or false are passed from callback()
//is getting here as bool
// the anonymous function below defines the functionality of the callback
function (bool){
if(bool){
alert("do stuff for when value is true");
}else {
//this condition is satisfied as 0 passed
alert("do stuff for when value is false");
}
});

Basically, callbacks() are used for asynchronous concepts. It is invoked on a particular event.

myFunction is also callback function. For example, it occurs on a click event.

document.body.addEventListener('click', myFunction);

It means, first assign the action to other function, and don't think about this. The action will be performed when the condition is met.

nodejs: Not able to read response from callback function in the main function

Try something like this,

import {
createTableService,
services,
ServiceResponse,
TableQuery
} from 'azure-storage';

getDatafromCosmosDB(): Promise<ServiceResponse> {
return new Promise(async (resolve, reject) => {
this.tableService.queryEntities(
this.tableName,
query,
null,
(error, _, response) => {
if (!error) {
resolve(response);
} else {
reject(error);
}
}
);
});
}

and invoke like,

this.getDatafromCosmosDB().then(data => {
console.log(data);
}


Related Topics



Leave a reply



Submit