2012-07-20 56 views
1

我正在做一些代碼與API交互, 爲了使用API​​,您需要獲得一個會話密鑰用於其餘的請求,會話密鑰將在一段時間,所以代碼也需要準備好實現。設計代碼工作流程

該代碼本身並不相關,也沒有API,因爲它是一個關於如何設計代碼流的問題,我正在尋找最好的方法來做到這一點。

我沒有代碼(JavaScript的/ node.js中),在這裏,但這裏是basicly它的外觀在僞代碼:

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; 
} 

然後使用它你:

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 */}); 

工人將處理所有繁重的你...