NodeJs simple example callback

Can someone give me a simple example of nodeJs callbacks, I have already searched the same on many websites, but could not understand it correctly. Please give me a simple example.

getDbFiles(store, function(files){ getCdnFiles(store, function(files){ }) }) 

I want to do something like this ...

+107
javascript asynchronous callback asynccallback
Nov 02 '13 at 7:10
source share
7 answers
 var myCallback = function(data) { console.log('got data: '+data); }; var usingItNow = function(callback) { callback('get it?'); }; 

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

Finally, use it on the following line:

 usingItNow(myCallback); 

Regarding Node-Styles Conventions

Costa asked what it would look like if we abided by the node callback conventions.

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

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 as 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 use is exactly the same as the previous one:

 usingItNow(myCallback); 

The only difference in behavior depends on which version of usingItNow you defined: the one that passes the "true value" (the Error object) for the callback for the first argument or the one that passes this null value for the error argument.

+175
Nov 02 '13 at 7:27
source share

A callback function is just a function that you pass to another function so that the function can call it later. This is usually observed in the asynchronous API ; the API call returns immediately because it is asynchronous, so you pass it a function that the API can call when it completes its asynchronous task.

The simplest example that I can think of in JavaScript is the setTimeout() function. This is a global function that takes two arguments. The first argument is a callback function, and the second argument is the delay in milliseconds. The function is designed to wait for the appropriate amount of time, and then calls the callback function.

 setTimeout(function () { console.log("10 seconds later..."); }, 10000); 

You may have already seen the above code, but just did not understand that the function you were passing through was called a callback function. We could rewrite the code above to make it more obvious.

 var callback = function () { console.log("10 seconds later..."); }; setTimeout(callback, 10000); 

Callbacks are used throughout Node because Node is built from the ground up to be asynchronous in everything it does. Even when talking to the file system. Therefore, a ton of internal Node APIs takes callback functions as arguments, rather than returning data that you can assign to a variable. Instead, it will call your callback function, passing the data you need as an argument. For example, you can use the Node fs library to read a file. The fs module provides two unique API functions: readFile and readFileSync .

The readFile function is asynchronous, and readFileSync clearly not. You can see that they intend to use asynchronous calls whenever possible, as they called them readFile and readFileSync instead of readFile and readFileAsync . The following is an example of using both functions.

Synchronous:

 var data = fs.readFileSync('test.txt'); console.log(data); 

The code above blocks the execution of the stream until all the contents of test.txt are read in memory and stored in the variable data . In Node, this is usually considered bad practice. Sometimes it’s useful, for example, when writing a quick small script to do something simple but tedious, and you do not care that you can save every nanosecond of time.

Asynchronous (with callback):

 var callback = function (err, data) { if (err) return console.error(err); console.log(data); }; fs.readFile('test.txt', callback); 

First we create a callback function that takes two arguments err and data . One of the problems with asynchronous functions is that it becomes harder to catch errors, so many callback APIs address errors as the first argument to the callback function. It’s best to check if err matters before doing anything else. If so, stop the callback and record the error.

Synchronous calls take precedence over exceptions, because you can just catch them with a try/catch .

 try { var data = fs.readFileSync('test.txt'); console.log(data); } catch (err) { console.error(err); } 

In asynchronous functions, this does not work. The API call returns immediately, so there is nothing to catch with try/catch . The correct asynchronous APIs that use callbacks will always catch their own errors, and then pass those errors to a callback, where you can handle it as you like.

In addition to callbacks, however, there is another popular API style that is commonly used called a promise. If you want to read about them, you can read the entire blog post that I wrote based on this answer here .

+99
Nov 03 '13 at 19:19
source share

Here is an example of copying a text file with fs.readFile and fs.writeFile :

 var fs = require('fs'); var copyFile = function(source, destination, next) { // we should read source file first fs.readFile(source, function(err, data) { if (err) return next(err); // error occurred // now we can write data to destination file fs.writeFile(destination, data, next); }); }; 

And what an example of using the copyFile function:

 copyFile('foo.txt', 'bar.txt', function(err) { if (err) { // either fs.readFile or fs.writeFile returned an error console.log(err.stack || err); } else { console.log('Success!'); } }); 

The generic node.js template assumes that the first argument to the callback function is an error. You must use this template because all control flow modules rely on it:

 next(new Error('I cannot do it!')); // error next(null, results); // no error occurred, return result 
+11
Nov 02 '13 at 7:35
source share

Try this example as simple as you can read, just copy save newfile.js do node newfile to run the application.

 function myNew(next){ console.log("Im the one who initates callback"); next("nope", "success"); } myNew(function(err, res){ console.log("I got back from callback",err, res); }); 
+7
May 13 '17 at 11:00
source share

we create a simple function like

 callBackFunction (data, function ( err, response ){ console.log(response) }) // callbackfunction function callBackFuntion (data, callback){ //write your logic and return your result as callback("",result) //if not error callback(error, "") //if error } 
+2
Sep 10 '17 at 14:14
source share
 const fs = require('fs'); fs.stat('input.txt', function (err, stats) { if(err){ console.log(err); } else { console.log(stats); console.log('Completed Reading File'); } }); 

'fs' is a node module that helps you read a file. The callback function ensures that your file named 'input.txt' is fully read before it is executed. The fs.stat () function is used to retrieve information about a file, such as file size, creation date, and modification date.

+1
Oct 31 '18 at 6:14
source share

callback is a function passed as a parameter to the Higher Order Function ( Wikipedia ). A simple callback implementation:

 const func = callback => callback('Hello World!'); 

To call a function, simply pass another function as an argument to a specific function.

 func(string => console.log(string)); 
0
May 7 '19 at 19:36
source share



All Articles