2012-07-20 55 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 */}); 

工人将处理所有繁重的你...