Looking for advice on callbacks

I have a programming question that isn’t necessarily squirrel specific. I’d be grateful for any suggestions.

I have a framework for translating http requests into requests to various hardware devices connected to an imp. It works well for requests of a single property (such as temperature, time, status).

to retrieve a single property value, I receive a request for a single property value:
`// This stuff is all pseudocode

req = { action = “get”, property = “temperature”, parameters = { various config values }, callback = function(response) { post-processing then send httpResponse(response)… } }

execute(req.action,req.property,req.parameters,req.callback);`

Where possible, all operations are asynchronous.

However, when I have a single request for multiple properties , I need to fire all of the requests off, each with its own callback. Once all the responses are in, I package them into a single aggregated response for the http Handler. I’m having trouble working how to align all the callbacks with each request.

I could simply use the same callback for each request, pushing the response onto the array of responses and counting that I have received enough responses. However, I know that the responses can arrive out of sequence, so this approach won’t fly.

`req = { action = “get”, properties = [“temperature”,“time”,“status”], parameters = { various config values }, callback = function(response) { post-processing then send httpResponse(response)… } }

respCount = req.properties.len();
respArray = array(respCount,{});
originalCallback = req.callback;
for (local i=0;i<respCount;i++){
local mycallback = function(response){

    // what can I put here to tell this particular instance of the callback which array-slot to put its slot in?
    // I know I can't use 'i'.  Must a key/index be in 'response'?
    respArray[???] = response


    // check if we now have all the responses
    if(--respCount==0)
        originalCallback(respArray);
}
// fire off each request
execute(req.action,req.properties[i],req.parameters,mycallback);

}`

I know that one approach is to put a “key” into the parameters, which is passed back as part of the response. I’d then use the key to align the appropriate response with the original request. I’ll resort to this if I can’t find another cleaner method. I would prefer it if each callback already “knew” where it should store its response in the array.

Looks like I’ll answer my own question here. Sometimes just trying to explain the problem to other helps you understand it better!

I’ve found that this works nicely:
`for (local i=0;i<respCount;i++){
local mycallback = function(response,index=i){

    respArray[index] = response

    // check if we now have all the responses
    if(--respCount==0)
        originalCallback(respArray);
}
// fire off each request
execute(req.action,req.properties[i],req.parameters,mycallback);

}`