Created
July 13, 2013 16:13
-
-
Save maxkueng/5991199 to your computer and use it in GitHub Desktop.
readylist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var ready = require('./ready'); | |
| var cdCache = {}; | |
| function getDiskData (discId) { | |
| cdCache[discId] = cdCache[discId] || ready(function (done) { | |
| setTimeout(function () { | |
| done(Math.random()); | |
| }, 2000); | |
| }); | |
| cdCache[discId].add(function () { | |
| console.log.call(this, arguments); | |
| }); | |
| } | |
| setInterval(function () { | |
| getDiskData("10"); // 10 is a disc id | |
| }, 500); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module.exports = ready; | |
| function ready (get) { | |
| var queue = [], | |
| results, | |
| state = 'waiting'; | |
| function completeQueue () { | |
| while (queue.length > 0) { | |
| queue.shift().apply(null, results); | |
| } | |
| } | |
| return { | |
| add: function (done) { | |
| queue.push(done); | |
| if (state === 'waiting') { | |
| state = 'running'; | |
| get(function () { | |
| state = 'ready'; | |
| results = arguments; | |
| completeQueue(); | |
| }); | |
| } else if (state == 'ready') { | |
| completeQueue(); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment