sparcut
sparcut

Reputation: 825

Is having a function as parameter for function like this syntactically acceptable?

I am trying to keep my development as modular and easy to use as possible, but I feel this might be taking it too far.

I am calling a function that uses a function which returns data as a parameter, which also uses a function that returns data. So they are nested as such:

append_vid(
    compile_data(
        request_data(vid_id)
    )
);

So, request_data() returns an object which compile_data uses to return another object to append_vid().

I am wondering if this is syntactically acceptable, since I have never seen someone nest functions as parameters like this before. Is there a more efficient or standardized method of achieving this without loosing the modularity of separate functions.

Upvotes: 0

Views: 39

Answers (1)

Sreekanth
Sreekanth

Reputation: 3130

That is completely valid syntax. If you are looking at synchronous calls.

function MethodOne(value) {
  console.log(value);
}

function MethodTwo(value) {
  console.log(value);
  return value * 4;
}

function MethodThree(value) {
  console.log(value);
  return value * 2;
}

MethodOne(
  MethodTwo(
    MethodThree(1)
  )
);

If you values are being returned from a async call, then you have to change the method signature and use promises. Here is an example for Async.

function MethodOne(value) {
  var promise = new Promise(function(resolve, reject) {
    setTimeout(function() {
      value = value * 4;
      console.log(value);
      resolve(value);
    }, 1000);
  });
  return promise;
}

function MethodTwo(value) {

  var promise = new Promise(function(resolve, reject) {
    setTimeout(function() {
      value = value * 2;
      console.log(value);
      resolve(value);
    }, 1000);
  });

  return promise;
}

function MethodThree(value) {
  console.log(value);
  var promise = new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve(1)
    }, 1000);
  });
  return promise;

}

MethodThree(1).then(MethodTwo).then(MethodOne);

Upvotes: 2

Related Questions