Hi stackoverflow community, i am trying to understand asynchronous , coding in nodejs , in particular i am trying to pass back results to the main function after making a call
i goggled around and found that this can be done either by using
Anyhow getting back to the main question, i have tired to implement the callback method, but i am doing something wrong. Please help
The code below is some sample i tried for the callback , but the outside result is never run. Basically i want the result of the calculation to be returned to r.
function calc (n1, n2 , r){
r = n1 + n2;
console.log("inside result %s",r);
}
calc(1,2,function(r){
console.log("outside result %s",r);});
Just a variation on the previous answer showing the callback effect:
function calc (n1, n2 , result){
var r = n1 + n2;
console.log("The first result is %s, ",r);
console.log("but for the final one we have to wait 2 seconds ...");
setTimeout(function() { //waits 2 seconds
r = r * r;
console.log('Done!');
result(r);
}, 2000);
}
calc(1,2,function(num){
console.log("The final result is %s",num);
});
console.log('... waiting, waiting ...'); //this shows up AFTER the first result but BEFORE the final one
Greetings.
Promises are not used in the core nodeJS libraries. Promises were considered along with callbacks but since there was no consensus, callbacks were chosen as being the easier to understand and less overhead. (callbacks were anything but easy when I first learned them)
In nodeJS, the general practice is for a callback function to have an err as the first parameter and return values following. The calc function above should be like this
function calc(a, b, callback) {
if (tired)
callback("Too tired to think."); // error return
else
callback(null, a + b); // success, note the null
}
To call it
calc(1, 2, function(err, sum) {
if (err)
console.error(err);
else
console.log("Sum is " + sum);
});
Note that function(err, sum) is passed as the callback argument to calc. To check if an error occurred simply do if (err), otherwise it was successful.
r = n1 + n2;
This assigns a new value to the r parameter.
You want to call the function:
r(n1 + n2);