2014-09-10 7 views
0

node.js에서 비동기 호출로 많은 고통을 겪고 있습니다. 나는 그것을 즐기야 만한다는 것을 이해하지만, 사실 node.js가 그것을 사용하도록 강요하고 또 다른 선택 사항이 없기 때문에 실제로 그것을 싫어한다.node.js redis 선택 및 동기화에서 비동기

다른 데이터베이스에서 smembers을 실행 해 봅니다. 그래서 여기서 내가 3 개의 데이터베이스를 모두 사용하고 있는지 확인하기 위해 _.after을 사용합니다. 그러나 그것은 작동하지 않습니다.

var redisfetcher = function(string, callback1) 
{ 
    var retrieved = [] 

    var callback = function(){ 
     callback1(retrieved) 
    } 

    var afterAll = _.after(3,callback) 

    for (var col=0; col<=2; ++col) { 
     client.select(col, function() { 
      client.smembers(string, function (err, replies) { 
      if(!err){ 
       retrieved.push(replies) 
       } 
      }) 
     afterAll(); 
     }) 
    } 

redisfetcher("offer", function(returnValue) { 
    console.log(returnValue) 
    }) 

나를 도와 주시면 감사하겠습니다.

동기화 모드에서 다음 코드를 실행하는 방법을 보여 주시면 감사하겠습니다.

답변

1

async 모듈을 사용하십시오. map 반대로 위의 코드 (동기와 혼동하지 마십시오) 순차적 mapSeries를 호출

var async = require('async'); 

async.mapSeries([0, 1, 2], function (db, done) { 
    // Here `db` will be `0`, or `1` or `2`, i.e. each element of the array. 
    // The `done` is an internal callback used by the `async` module 
    // to track whether a particular element of the array is completed 
    // to be processed. When you're "done" consuming the `db` element of the 
    // array, you must call `done` to indicate that `async` can now give you 
    // yet another element to consume, if there is any left to process. 
    // When all elements are processed, `async` calls the final function 
    // passes to it as the last argument. For more information refer to 
    // very detailed docs of `async` module at 
    // https://github.com/caolan/async#mapSeries. 
    async.waterfall([ 
     function (cb) { 
      client.select(db, cb); 
     }, 
     function (cb) { 
      client.smembers(string, cb); 
     } 
    ], done); 
}, function(err, resultArr) { 
    err && console.trace(err); 

    // `resultArr` now contains 3 replies. 
}); 

공지 사항, 평행하지. 다른 데이터베이스를 선택하면 이러한 비동기 호출이 충돌 할 수 있기 때문에 귀하의 경우 각 DB마다 다른 Redis 연결을 사용하는 것이 좋습니다. 이로 인해 다른 데이터베이스 대신 동일한 데이터베이스에 대해 명령이 실행될 수 있습니다. 동일한 데이터베이스에 대해 여러 명령을 실행하면 단일 연결이 정상입니다.

연결 풀링의 경우 node-pool을 사용하십시오.

+0

정말 고맙습니다.하지만 실제로 (db, done) iterator, db -is 데이터베이스 인덱스, 완료 여부를 이해하지 못합니까? 내가 올바른지 확인하면 폭포의 마지막 요소의 콜백이 콜백으로 사용됩니다. – com

+0

코드에 자세한 주석을 추가했습니다. – Eye

+0

고맙습니다. 몇 분 남았습니다. 비슷한 질문을보세요. http://stackoverflow.com/questions/25765027/node-js-async-mapseries-of-smembers – com