2

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

  1. callbacks
  2. promises ( promises as i understand has been removed from the nodejs , hence need to add the library using NPM package )

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);});
1
  • Maybe you're just experimenting, but the function you're writing isn't asynchronous, so you could just return the result. You only need to use the callback approach if your function itself calls other asynchronous methods. Commented Dec 12, 2012 at 2:47

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0
r = n1 + n2;

This assigns a new value to the r parameter.

You want to call the function:

r(n1 + n2);

2 Comments

thanks SLaks for the reply, i tested it and it worked, but i am wondering , given i keep the same structure of code, is there a way to print out the result of the calculation from the module, so i get both an internal result and external result
@JoyDThi: Put it in a variable?
0

Let me share what I learnt working here at Oodles Technologies. Let us take an example.

Let there are four functions functionCall, doSomeworkOne, doSomeworkTwo, doSomeworkTwo and they are performing some IO tasks.

function doSomeworkThree functionCall depends doSomeworkOne, doSomeworkOne depends doSomeworkTwo, doSomeworkTwo depends doSomeworkThree. To make these sync, callback function passed as parameter in all functions.

function functionCall(data, callback){
    ...........
    ...........
    doSomeworkOne(data, callback);
}


function doSomeworkOne(data, callback){
    ...........
    ...........
    doSomeworkTwo(otherData, callback);        
}


function doSomeworkTwo(otherData, callback){
    ...........
    ...........
    doSomeworkThree(otherData, callback);
}

<span style="font-size:16px;"><span style="font-family:arial,helvetica,sans-serif;"> function doSomeworkThree(otherData, callback){
    ...........
    ...........
    callback(result);
}
</span></span>

function callback(data){
    return data
}

Callback, on the other hand is good. The main problem with callbacks is: nested inside of callbacks, nested inside of callbacks. In nested callbacks, it is very tough to test/maintain the codes.

Here the Promises comes. Promises provide us with a cleaner and more robust way of handling async code. Instead of using a callback. And also handling errors with promises is very easy.

function functionCall(data){
    doSomeworkOne(data).then(function(data){
        return doSomeworkTwo(data);
    }).then(function(data){
        return     doSomeworkThree(data);
    }).catch(function(e) {
        // error handle    
    });
}


function doSomeworkOne(data){
    retrun new Promise(function(resolve, reject){
        ...........
        ...........
        if(error){
            reject(error);        
        }else{
            resolve(success);
        }
    })        
}


function doSomeworkTwo(data){
    retrun new Promise(function(resolve, reject){
        ...........
        ...........
        if(error){
            reject(error);        
        }else{
            resolve(success);
        }
    })        
}


function doSomeworkThree(data){
    retrun new Promise(function(resolve, reject){
        ...........
        ...........
        if(error){
            reject(error);        
        }else{
            resolve(success);
        }
    })        
}

Note: Promises and Callbacks are not fundamentally different. Promises is advisable in nested callbacks where you want to perform a series of actions. I hope this will help you. Thanks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.