test.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. 'use strict';
  2. var Saferphore = require('./index');
  3. var assert = function (x) { if (!x) { throw new Error(); } };
  4. var basicTest = function () {
  5. var sem = Saferphore.create(4);
  6. var out = [];
  7. (new Array(10)).join().split(',').forEach(function (x,y) {
  8. sem.take(function (returnAfter) {
  9. out.push(y);
  10. setTimeout(returnAfter(function () {
  11. if (out.length === 10) {
  12. if (out.join() !== "0,1,2,3,4,5,6,7,8,9") { throw new Error(); }
  13. }
  14. }));
  15. });
  16. });
  17. if (out.join() !== "0,1,2,3") {
  18. throw new Error(out.join());
  19. }
  20. };
  21. var doubleCallTest = function () {
  22. var sem = Saferphore.create(4);
  23. var catcher = setTimeout(function () {
  24. throw new Error();
  25. }, 1000);
  26. sem.take(function (returnAfter) {
  27. setTimeout(returnAfter(function () {
  28. setTimeout(function () {
  29. clearTimeout(catcher);
  30. try { returnAfter()(); } catch (e) { return; }
  31. throw new Error();
  32. });
  33. }));
  34. });
  35. };
  36. var doubleCallbackTest = function () {
  37. var sem = Saferphore.create(4);
  38. var catcher = setTimeout(function () {
  39. throw new Error();
  40. }, 1000);
  41. sem.take(function (returnAfter) {
  42. var wrapped = returnAfter();
  43. wrapped();
  44. try { wrapped(); } catch (e) { clearTimeout(catcher); return; }
  45. throw new Error();
  46. });
  47. };
  48. basicTest();
  49. doubleCallTest();
  50. doubleCallbackTest();