質問

Using JavaScript (node, but same issue in browser), I have a list of Users. Each User object must be used to log in to an exchange to retrieve it's Orders and then, if any are found, process them. Once logged in to an exchange, a loop is established so that orders can be retrieved from all exchanges for all users at regular intervals until the process is killed.

e.g.:

var users = [ { id:1, throttle: 20 }, { id: 2, throttle: 45 } ];
var exchanges = [ 'au', 'uk' ];

would mean 4 loops running with the follow settings::

processor 1 - id: 1, exchange 'au', throttle: 20
processor 2 - id: 1, exchange 'uk', throttle: 20
processor 3 - id: 2, exchange 'au', throttle: 45
processor 4 - id: 2, exchange 'uk', throttle: 45

For each case, I loop every x minutes (based on the throttle).

I have been using caolan's async library to do this - the async.each, async.forever, and async.parallel functions specifically; but am struggling with passing scope between them.

The issue is that a user will have an exchange assigned on first pass (e.g. 'au') and run fine. On any subsequent loop the function picks up a different user to the one it should.

I have created a fiddle to demonstrate the issue: http://jsfiddle.net/RnMb9/7/

After the first pass (User 1: processing au exchange (every 20 seconds).) 'au' is never seen again.

Any ideas on how to correct this context issue? I have been playing around with binding the user in all areas I can but to no avail.

役に立ちましたか?

解決

….each(users, function(user) {
    ….each(exchanges, function(exchange) {
        …
        user.exchange = exchange;

That's your problem. In each (inner) loop turn, you're overwriting the .exchange value of the same user object. To solve this, either clone your object, or make the exchange a separate argument to the processor instead of passing it as a part of the user object.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top