【发布时间】:2012-08-13 17:58:07
【问题描述】:
我正在努力思考如何使异步编程工作。
在我当前的用例中,我的函数可能每秒被调用多次,并且它们具有依赖于多个变量的回调,这些变量可能会在它们之间发生变化。
一个简化的例子:(为简洁起见使用coffeescript)
doSomething = (requestor, thing, action, callback) ->
thing.takeAction action, (result) ->
# actually a lot of times this nests down even further
requestor.report result
callback result
如果在 thing.takeAction 返回结果之前使用不同的数据多次调用 doSomething,我认为我不能依赖请求者和回调仍然是我需要的相同事物。 对吗?
为了避免这种情况,我需要以某种方式将请求者和回调注入到 takeAction 的回调中。 这有可能吗?
我想到了做类似的事情
doSomething = (requestor, thing, action, callback) ->
thing.takeAction action, (result, _requestor = requestor, _callback = callback) ->
_requestor.report result
_callback result
但这当然只是一个 CoffeeScript hack,根本不起作用。
顺便说一句,我试图使用 caolan/async 模块来帮助我解决这个问题,但事实仍然是,我在回调中经常需要比 async 提供的变量更多的变量。 喜欢:
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?
});
}
它仍然给我留下同样的问题。那我该怎么做呢?
感谢您的宝贵时间。
【问题讨论】:
-
“动作还是一样”是什么意思?您是否担心您引用的
action对象的某些字段可能会在事件循环中的其他位置发生变化?如果是这种情况,显而易见的解决方案是在doSomething正文中克隆此action对象。 -
是的,动作对象一直在变化,甚至在回调被调用之前。甚至在第一个回调返回之前,该函数也会被不同的动作对象调用。就像
doSomething(x, y, action1, cb); doSomething(x, y, action2, cb); doSomething(x, y, action3, cb);我假设这也会改变回调上下文中的'action'变量。 ... doSomething-body 中的克隆仍然会在回调中持续存在吗?因为我现在正在跟踪一些奇怪的错误,这让我认为它没有。
标签: javascript node.js asynchronous callback coffeescript