2012-07-20 5 views
1

API와 상호 작용할 코드를 작성 중입니다. API를 사용하려면 나머지 요청에 사용하는 세션 키를 가져와야합니다. 그러면 세션 키는 잠시 동안 코드를 재실행 할 준비를해야합니다.코드 작업 흐름 설계

코드 자체는 코드 흐름을 디자인하는 방법에 대한 질문부터 관련성이 없으며 API도 아닙니다. 최선의 방법을 찾고 있습니다.

function getResult { 
    data = foobar 
    return getData(data, callback) 
} 

function getData(data, callback) { 
    *building query (including the session-key) and getting data via http* 
    if error == noauth 
    auth() 
    // What should happen here, I need to rerun the query 
    else 
    callback(result) 
} 

function auth { 
    data = foobar 
    getData(data, callback(?)) 
    // it returns a session-key to use 
    //What should happen here? 
} 

답변

0

내가 할 것 같은 뭔가 :

function GetAuth(auth_params) 
{ 
    // get session key 
    return session key; 
} 

function MyAPIWorker(auth_params) 
{ 
    this._auth_params = auth_params; 
    this._current_auth = null; 
} 

MyAPIWorker.prototype.do(action) 
{ 
    if (this._current_auth == null) 
    { 
    this._current_auth = GetAuth(); 
    } 
    var result = action(this._current_auth); 
    if (result == no_auth_error) 
    { 
    this._current_auth = GetAuth(); 
    result = action(this._current_auth); 
    } 
    return result; 
} 

는 의사의 모양을

나는 코드 (자바 스크립트/Node.js를)가 없습니다 여기 그러나 여기 basicly입니다 그것을 사용하기 위해 당신이 할 :

worker = new MyAPIWorker(/* auth params here */); 
worker.do(function (sessionKey) { /* do something with session key */}); 
/** blah blah **/ 
worker.do(function (sessionKey) { /* do other something with session key */}); 

은 작업자가 당신을 위해 모든 무거운 처리합니다 ...