Last active
August 29, 2015 14:00
-
-
Save tyler-johnson/11350923 to your computer and use it in GitHub Desktop.
Wait on several async items to complete. Plays nice with most async JavaScript including promises.
This file contains 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
function asyncWait(onEmpty) { | |
var counter = 0; | |
setTimeout(callback(), 0); | |
return callback; | |
function callback(cb) { | |
var called = false; | |
++counter; | |
return function() { | |
if (called) return; | |
called = true; | |
--counter; | |
if (typeof cb === "function") cb.apply(this, arguments); | |
if (!counter && typeof onEmpty === "function") onEmpty(); | |
} | |
} | |
} |
This file contains 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 assert = require("assert"); | |
describe("wait", function() { | |
it("defer a call to onEmpty by default", function(done) { | |
var isAfter = false; | |
asyncWait(function() { | |
assert(isAfter, "onEmpty function was called prematurely."); | |
done(); | |
}); | |
isAfter = true; | |
}); | |
it("immediately call functions passed to the callback method on run", function(done) { | |
var isAfter = false; | |
var proxy = asyncWait(done)(function() { | |
assert.equal(isAfter, false, "Passed function was not called immediately."); | |
}); | |
process.nextTick(function() { | |
proxy(); | |
isAfter = true; | |
}); | |
}); | |
it("pass same context and arguments through proxy callback", function(done) { | |
var context = {}, arg1 = {}, arg2 = {}; | |
var proxy = asyncWait(done)(function(a, b) { | |
assert.strictEqual(this, context, "Context was not the same."); | |
assert.strictEqual(a, arg1, "Argument 1 was not the same."); | |
assert.strictEqual(b, arg2, "Argument 2 was not the same."); | |
}); | |
process.nextTick(function() { | |
proxy.call(context, arg1, arg2); | |
}); | |
}); | |
it("wait for multiple async operations to finish", function(done) { | |
var finished = [ false, false, false ]; | |
var callback = asyncWait(function() { | |
assert.deepEqual(finished, [ true, true, true ], "One or more callbacks wasn't fired."); | |
done(); | |
}); | |
setTimeout(callback(function() { finished[0] = true; }), 10); | |
setTimeout(callback(function() { finished[1] = true; }), 25); | |
setTimeout(callback(function() { finished[2] = true; }), 100); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment