2014-10-31 9 views
0

질문 제목이 모호한 경우 미안하지만 어떻게 말씀 드릴 지 모르겠습니다.노드 생성자가 명령을 보내기 전에 API에 연결될 때까지 기다리십시오.

json-rpc api와 대화하는 NPM 모듈을 작성 중입니다. 이것이 현재 설정입니다.

// The module 
function MyModule(config) { 
    // do some connection stuff here 
    connected = true 
} 

MyModule.prototype.sendCommand = function() { 
    if(connected) { 
     // do command 
    } else { 
     // output an error 
    } 
} 

module.exports = MyModule; 

// The script interacting with the module 
var MyModule = require('./MyModule'); 
var config = { 
    // config stuff 
}; 
var mod = new MyModule(config); 
var mod.sendCommand; 

명령은이 시점에서이 연결되지 않은 것처럼, 나는이 비 블록 아키텍처를 NodeJS '비동기로 인해 내가 아마 기다릴 약속을 사용할 필요가 있다고 가정 전송하지 않습니다 API에서 응답, 어디서 구현할 수 있습니까? 제 모듈에서 그것을합니까? 아니면 모듈과 상호 작용하는 스크립트에서합니까?

+0

로 함수를 호출 - 그건 나쁜 매너 : 그것은 "실제로 가능한되면 데이터를 겨. 그 해결에 약속을하고 sendCommand와 같은 것에'thatPromise.then (function() {'을 써야 결과가 해석되면 항상 명령을 보내 게됩니다.) kriskowal의'q- 연결 '. –

답변

1

콜백이나 약속 또는 그와 비슷한 것을 사용해야 연결이 완료되었음을 알 수 있으므로 해당 콜백을 통해 시작된 추가 코드에서 연결을 사용할 수 있습니다. 그것은 일반적으로 생성자에서 비동기 물건을 수행하는 가장 좋은 방법을 고려하지 않지만

, 수행 할 수 있습니다

function MyModule(config, completionCallback) { 
    // do some connection stuff here 
    connected = true 
    completionCallback(this); 
} 

var mod = new MyModule(config, function(mod) { 
    // object has finished connecting 
    // further code can run here that uses the connection 
    mod.sendCommand(...); 
}); 

보다 일반적인 디자인 패턴이 생성자에서 연결을 넣어하지 않는 것입니다 하지만, 그냥하는 방법을 추가 :

function MyModule(config) { 
} 

MyModule.prototype.connect = function(fn) { 
    // code here that does the connection and calls 
    // fn callback when connected 
} 

var mod = new MyModule(config); 
mod.connect(function() { 
    // object has finished connecting 
    // further code can run here that uses the connection 
    mod.sendCommand(...); 
}); 
0

deali에 대한 결과 핸들러는 없습니다 "호출 함수"를 할 약속, 사용 노드의 프로그래밍 모델하지만 "전화 기능을 사용하지 않는

MyModule.prototype.sendCommand = function(handler) { 
    if(connected) { 
    // run stuff, obtain results, send that on: 
    handler(false, result); 
    } else { 
    // output an error, although really we should 
    // just try to connect if we're not, and say 
    // there's an error only when it actually fails. 
    handler(new Error("ohonoes")); 
    } 
} 

을 다음 생성자에 연결하지 마십시오

var MyModule = require('./MyModule'); 
var mod = ... 
mod.sendCommand(function(err, result) { 
    // we'll eventually get here, at which point: 
    if (err) { return console.error(err); } 
    run(); 
    more(); 
    code(); 
    withResult(result); 
});