0

I have found this code on SO :

function dothings(things, ondone){
    function go(i){
        if (i >= things.length) {
            ondone();
        } else {
            dothing(things[i], function(result){
                return go(i+1);
            });
        }
    }
    go(0);
}

I couldn't figure out how I should define dothing function. Should it be like this :

function dothing(elem)
{
   //do things with elem
}

Or should I somehow indicate the function(result), if yes how should I do that? Thanks in advance.

jason
  • 6,962
  • 36
  • 117
  • 198

4 Answers4

1

do it like this,

function dothing(elem, cb)
{
   //do things with elem
   // return the result
   cb(...somedata)
}
Anurag Awasthi
  • 6,115
  • 2
  • 18
  • 32
1

The dothing is an asynchronous function here.

In asynchronous function signature, a callback is one of the params.

Also in order to return a value from a async function, the callback needs to be called with the value to be returned. A return statement does not make sense in async function.

The definition can look like:

function dothing(elem, callback){
     // Your logic to process elem
     // var result = some_custom_logic(elem);
     callback(result);
}
Jay
  • 1,478
  • 1
  • 10
  • 9
  • And I don't need to define the functionality of `callback` in somewhere else right? Because it's being defined inside `dothings`? – jason Aug 11 '17 at 07:48
  • Yes, it is true. The definition of callback method is being passed when dothing is invoked inside the `dothings`. – Jay Aug 11 '17 at 07:50
  • One more question : Should `result` essentially be meaningful? I'm just modifying an external array in my actual code. – jason Aug 11 '17 at 13:20
  • It is not a requirement to pass a result. I just showed a way to pass result if there is a need. – Jay Aug 11 '17 at 13:22
1

You can define dothing like this

function dothing(elem, callback){
    //result =  do stuff with elem
    callback(result);
}
marvel308
  • 10,288
  • 1
  • 21
  • 32
1

It looks a bit overcomplicated, because it calls the function over and over again and does not work for the elements of things and and in the reverse order for calling ondone function.

function dothings(things, ondone) {
    function go(i) {
        if (i < things.length) {
            console.log(i, things[i]);
            go(i + 1);
            ondone(i);
        }
    }

    go(0);
}

dothings([1, 2, 3, 4], function (v) { console.log(v, 'done'); })
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392