Trying to understand the callback function

I’m trying to work out how to pass runtime parameters to a common callback function.

For example, if I use imp.wakeup(interval, function() { }) I believe I can define which data to use inside the function call as in

function foo() { foreach (i in myarray) { imp.wakeup(10 + i, function() {server.log("array data is" + myarray[i]; }); } }

However if I want to create a common callback function, how do I pass the parameter “i” to the callback function as the wakeup function is merely imp.wakeup(10 + i, mycallbackfunction)

Yes, it is possible. Although, your code for foo is unlikely to work. If you say: foreach(i in myarray) you’ll iterate through the array with i as each element, not the index of each element. Thus, you can’t reference myarray[i], just use i alone. Alternately, you can get both the index and the value by using foreach (index,value in myarray).

I’m guessing what you are wanting to do, but here’s a possible solution:

`function foo() {
     foreach (i,v in myarray)
          imp.wakeup(10 + i, function(value=v) {
               server.log("array data is" + value)
          })
}`

:slight_smile:

@coverdriven thanks for the explanation. Yes my rushed example for foo() was not well thought out as you have pointed out.

What I was hoping for was to see if there is a way to pass parameters, such as “value=v” through callback function, which I had named mycallbackfunction, rather than using the embedded function () {} method inside my imp.wakeup calls.

Reason being is that I have numerous locations in my code where use the wakeup method that needs to implement the same function, but with different parameters so would like to avoid duplication / cut n paste of that code snippet if possible.

Why not wrap the wakeup in your own function?

`function mywakeup(timeout,value){
  imp.wakeup(10+timeout,function(value=value){ 
    server.log("array data is" + value)
  })
}

function foo() {
     foreach (i,v in myarray)
          mywakeup(i,v)
}`

Very clever. @coverdriven thanks to tip.