设计代码工作流程

Designing code work flow

本文关键字:工作流程 代码      更新时间:2023-12-04

我正在制作一些代码来与API交互,为了使用API,您需要获得用于其余请求的会话密钥,该会话密钥将在一段时间后变为无效,因此代码也需要准备好重新验证。

代码本身与API无关,因为这是一个关于如何设计代码流的问题,我正在寻找最好的方法。

我这里没有代码(javascript/note.js),但这里是它在伪代码中的基本外观:

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

我会做一些类似的事情:

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

工人将为你搬运所有重物。。。