I am trying to wrap my head around how to make asynchronous programming work.
In my current use-case, I have functions that get called potentially multiple times per second and they have callbacks that rely on multiple variables that could change in between them.
A simplified example: (using coffeescript for brevity)
doSomething = (requestor, thing, action, callback) ->
thing.takeAction action, (result) ->
# actually a lot of times this nests down even further
requestor.report result
callback result
If doSomething gets called multiple times with different data before thing.takeAction returns its result, I assume I can't rely on requestor and callback still being the same things I need them to be. Correct?
To circumvent this I'd need to somehow inject requestor and callback into takeAction's callback. Is that possible somehow?
I got the idea of doing something like
doSomething = (requestor, thing, action, callback) ->
thing.takeAction action, (result, _requestor = requestor, _callback = callback) ->
_requestor.report result
_callback result
But that of course is just a CoffeeScript hack and doesn't work at all.
By the way, I was trying to use the caolan/async module to help me with this, but the fact still remains that I often need more variables in the callbacks than async lets me provide. Like:
doSomething = function(requestor, thing, action, callback) {
// this might not need a waterfall, but imagine it would have nested further
async.waterfall(
[
function(next) {
thing.takeAction(action, function(result) {
// How can I know that action is still the same?
next(null, result);
});
},
function(result, next) {
requestor.report(result); // requestor still the same?
next(null, result);
}
],
function(err, result) {
callback(result); // callback still the same?
});
}
It still leaves me with the same problem. So how do I do this?
Thank you for your time.
actionobject you've referenced could change somewhere in other place in the event loop? If this is the case, the obvious solution would be to clone thisactionobject in thedoSomethingbody.doSomething(x, y, action1, cb); doSomething(x, y, action2, cb); doSomething(x, y, action3, cb);I'm assuming that will also change the 'action' variable in the context of the callback. ... Will the clone inside the doSomething-body still persist in the callback though? Because I'm tracking some strange bugs right now that make me think it doesn't.