Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to collect multiple callbacks to call once a task is done
    primarykey
    data
    text
    <p>I can't seem to find a general solution to this problem, even though I feel like I can't be the first to come across this. I also suspect it might be I'm taking the wrong approach in the first place here. Let me know.</p> <p>I have an Expressjs App the interacts with various APIs (mostly OAuth2). Once a request comes in the App checks if it has an access token to fetch data from an API. In case the token is expired it will request a new one.</p> <p>Now, when my App receives a second request in the meantime, requiring the exact same API, I want to avoid making a second call for an access token. </p> <p>What I do is use a "Collector" where callbacks can be stored for a given key. The first request to store a callback for a key gets a collector callback to invoke once it has finished the task. All subsequent callbacks are enqueued and called later on with the collector callback.</p> <p>This is the simple Collector class (CoffeeScript)</p> <pre><code># Collect callbacks for tasks and execute all once the job is done module.exports = class Collector constructor: ()-&gt; @tasks = {} add: (key, callback)-&gt; unless @tasks[key] # Initiate callback list for the key with first callback @tasks[key] = [callback] return ()=&gt; # Call all collected callbacks for the key (callback.apply {}, arguments for callback in @tasks[key]) # Reset callback list @tasks[key] = null else # Add callback to existing list @tasks[key].push callback return false </code></pre> <p>I'm not sure if storing the callbacks inside this class is the right way, but to use a database (Redis) I would have to find a way to store callbacks…</p> <p>Is there a better way to invoke multiple callbacks once a job is done?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload