{"_id":"@async-cancellables/ct","_rev":"4-8c5d7f7a0c7eeaafdcb8af3dfba5069c","name":"@async-cancellables/ct","dist-tags":{"latest":"2.3.0"},"versions":{"2.0.0":{"name":"@async-cancellables/ct","version":"2.0.0","description":"CancellationToken class","main":"index.js","type":"module","repository":{"type":"git","url":"git+https://github.com/vuwuv/async-cancellables.git","directory":"packages/ct"},"keywords":["async","cancellable","CancellationToken","cancellation"],"author":{"name":"vuwuv"},"license":"MIT","bugs":{"url":"https://github.com/vuwuv/async-cancellables/issues"},"homepage":"https://github.com/vuwuv/async-cancellables#readme","engines":{"node":">=18.0.0"},"gitHead":"cca86a13c78c2c9eab5806f11d8f7a298f20aec0","_id":"@async-cancellables/ct@2.0.0","_nodeVersion":"18.13.0","_npmVersion":"9.3.1","dist":{"integrity":"sha512-Ep2wvRvcJhLJafuDsgl8YcQkeS8rmUQN4CuAm2xtDCE0cPT1S+qn52mnp+lMeZn1kXsvkE6lVn7sEieSVHl64Q==","shasum":"e6d530a40d535ee285fa87324187ada156709b1e","tarball":"https://registry.npmjs.org/@async-cancellables/ct/-/ct-2.0.0.tgz","fileCount":5,"unpackedSize":29442,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIB889NrbNvjHBt4D6LpN0tbPebvUDAJs5zyvX/fdnKjBAiEA7psaheCgROJGZxHA8jLQ7XjGtgP0p4ABcD9raoL6h6I="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJkBGRyACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmoUlA//WI5YEG6481j0BXlO8bY3omT8CthoPOTijd1jP6QBK7/JI2YY\r\nC2UZvsobEDWTeZzlNx0WsBGPjc29JNBd5Mp3CE8Tj2V8OiTEaP66H88aJ4hZ\r\n/WjzAxI5By7zbMRaXPsqzOnEaAnYigT/M078j8sF0M2bncUymvMaHB2rJrSk\r\nzZfrE+zZTWlj9/88g5pvZ/h4W614SwipLI3QZxJREEusFrwClKbpAxEY2Q5t\r\nkfGB2BE59oPiD2WiHYm2jrGw+0Vqzr7e6/C+qmv+t0XAL1O+0SF+9Uql8NWm\r\nx4qcVpK3IDTQuwmWJbXMbG507yVXl4puQRXJhe1NI38fI+rdl7y9HwN0bCPh\r\ncCCv0Ift0HzAwJQWgt/OS+rAM1UdnmO3iqcHRzQDFSulGYZEb2ZuzZI5TeC8\r\ny7WJfru1pzNysln8iHzBqopwcoMz95+hco/uinb98CuY/73qxW6xUDqlMXNn\r\nT7SDXnwuqUV1ubhZMrs+HZ2q4iuMOc2JohPFwJdxn+O5wF9cJOeVBkyhcIXw\r\n7E+RGy/0Z6a/ls36fxBR+8TKPYqQNh1UUIR2CE9XxjImbhO9bDVCxUgoTflN\r\njn1FRquLiuSiBlX5DNB7fNMt0UVccJHfju/FolODQ0yyFoj4t7SH0sRpubmC\r\n176e+yy0OqSW0iu4/WT3xCEWDwShcWdNBps=\r\n=TBpD\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"vuwuv","email":"vkhubb@gmail.com"},"directories":{},"maintainers":[{"name":"vuwuv","email":"vkhubb@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ct_2.0.0_1678009458758_0.8409773827442617"},"_hasShrinkwrap":false},"2.1.0":{"name":"@async-cancellables/ct","version":"2.1.0","description":"CancellationToken class","main":"index.js","type":"module","repository":{"type":"git","url":"git+https://github.com/vuwuv/async-cancellables.git","directory":"packages/ct"},"keywords":["async","cancellable","CancellationToken","cancellation"],"author":{"name":"vuwuv"},"license":"MIT","bugs":{"url":"https://github.com/vuwuv/async-cancellables/issues"},"homepage":"https://github.com/vuwuv/async-cancellables#readme","engines":{"node":">=18.0.0"},"gitHead":"286a1b8f801a432827adb845c47074d85aa338c6","_id":"@async-cancellables/ct@2.1.0","_nodeVersion":"18.13.0","_npmVersion":"9.3.1","dist":{"integrity":"sha512-cucR8XakM3h1iJGKTHo7844N5tO3TmlmpHgRmEpOU3ZNMul1pcvtg9nCBqrYRwEB+ita8n3VwSRvd44uzTPCqQ==","shasum":"56700d02b25acd45a5d9098772d8a354eeb38f91","tarball":"https://registry.npmjs.org/@async-cancellables/ct/-/ct-2.1.0.tgz","fileCount":5,"unpackedSize":31995,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCICktJjXYkhOFFa44E8r/feWH/PkLjodwvybYHAuI6PAvAiEAg8FmV54Cb9uX/Do6sR8ZwCmbLqfUjBSc76mUm/Jt1fQ="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJkB6W1ACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2Vmrlnw//SY3e2eVMJhDHOoy0k96WeyG/OOibkuyQRY25wgCCY5IfqBq8\r\n081cXp20DwDxLLdnezpO24/uwmjMRYqb4ymxdJ+EKDX4ev6qELFgcRAMJe7J\r\nmM+r33odczrXziqFfK5pwiLXPEMGGmf67Ufx1R9JaBE52vQD6TYKYU9nvOmK\r\nznk1ATjfPJy/qjcWz4hYSxAYM2SzeRnOiIFy/vF2qIDXt24SW1cKC0G93PUA\r\nUhPBCa648Zm79cncU3Sepm+Qa87C7cY0EV26UvfjgUyukorXzncaNYtIeIHb\r\nYaoUxERqXsgtlChCAPfkiAWjp1CkdiYe+WStbOkltTXmEFJBvy8j/xGJyF40\r\n4hyeuzir8f+ABxp2oHJkFKAqMluqt78c7b7hAFdVAjo50Dc5LLMlvG3WyFu9\r\nSydtYXd3uljO8k1nTGDQyHW9piJ41l6DQyEGshxqAyHgb84W3oMJsW8RTqIb\r\nxACt2c6UbXEmt/w/LA7CloF5i+XHsMY+kYGCGRoHSMXED40Sr7eIjGUC/gei\r\nzZDTCKk2iPR7v9rzI5kI+22X+pwT+7puyiFDNuy7U5SLudXMoEV9oxNt2vyn\r\nd9RD0GHvoJhxFJzMvBU8OpalhXQ9aVgajJfiqKj8kG4wSvMvryJOUJX8gIlI\r\nfTg8axyZous3HqvM4QTAIQ9J5MZX4p1gd5w=\r\n=f0RQ\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"vuwuv","email":"vkhubb@gmail.com"},"directories":{},"maintainers":[{"name":"vuwuv","email":"vkhubb@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ct_2.1.0_1678222773513_0.05097354103872842"},"_hasShrinkwrap":false},"2.2.0":{"name":"@async-cancellables/ct","version":"2.2.0","description":"CancellationToken class","main":"index.js","type":"module","repository":{"type":"git","url":"git+https://github.com/vuwuv/async-cancellables.git","directory":"packages/ct"},"keywords":["async","cancellable","CancellationToken","cancellation"],"author":{"name":"vuwuv"},"license":"MIT","bugs":{"url":"https://github.com/vuwuv/async-cancellables/issues"},"homepage":"https://github.com/vuwuv/async-cancellables#readme","engines":{"node":">=18.0.0"},"gitHead":"286a1b8f801a432827adb845c47074d85aa338c6","_id":"@async-cancellables/ct@2.2.0","_nodeVersion":"18.15.0","_npmVersion":"9.3.1","dist":{"integrity":"sha512-xGxtxKO/UFrsFNE+RtVDK7UGfqa2u2H7TDu1RCe7eDUEWp9hc0H3O+jUyJkGDZ/qM4LwVmMNn+rkGI6bMSBFmQ==","shasum":"a59fb16781bf38b007c7b8901c1c8fbcc65ba9f3","tarball":"https://registry.npmjs.org/@async-cancellables/ct/-/ct-2.2.0.tgz","fileCount":5,"unpackedSize":32703,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCcrlO6txfDCSP2XnN4qzO++KqHIXntG0UQrdbgRKj6RwIgSn+kWdVPQ39+k0xOJZD/wWCraeXkTWrWJ+bVmZNIoME="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJkEeARACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmpNCw//bbyJZT0q8VqAt/74smyfo5G7+6kFJ0L3RIwta1wIL9/0nAJJ\r\nhcQTDro4VWfUho/c3diM2hFBJLsZbFD4ra6NpxsP2IA2XZvLoUpGf0Jo+Eui\r\n8Jez9I7PSf/QRLUl3g49De/vBWFfbHa4VxyAJh1ZYE7XnS5n3ioiiOat5OXf\r\nHjBf95poDrPq5pK6utzdK+26/G7n95FcftAqJW7gwz93ZjZuvN3eUHymM84T\r\n6OQ6vj0mt+qSdA01XK4xzTEAmF/mtARCQ5zJEXuj5laAHNhLLVvYzwvqBIFf\r\nKdmRK7crb9NCdAU/IYutmsXBz7Z+0XcFDyl7eO/rC2MaVrdGsAT91S8tKGRQ\r\nGh8IntYu0IQ3xRcqkRF6aTtoW4dzBCskIY+GkGOvQrWRPaZCac4Eud5Z79ND\r\njbwsbBj4oC6SZu1L5FyFF801Ma5NzWNkAVDtprk5NVw25ivVUCmZV7m4LPCZ\r\np2SAljEbqA5VTurK7iiy3OpSI6wxMD09i/KpfdqEOljyQbvl1pYnXZjyHs9X\r\nor/k+mapvxCMDAt0dNeTPDxnteHbQNKE4N/hPc2XPzVmtJhFsL0+jY3iPPC/\r\nX3yKTkYZ5xida2D9JJePy13Ea9TKL8i/PCvomU7pb9zk8IqpyIzhGMN5CQk1\r\nFh9fzchUnIKNGpaplrdMR31gL4OyM+42ICs=\r\n=JV/T\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"vuwuv","email":"vkhubb@gmail.com"},"directories":{},"maintainers":[{"name":"vuwuv","email":"vkhubb@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ct_2.2.0_1678893072892_0.17673948556633134"},"_hasShrinkwrap":false},"2.2.1":{"name":"@async-cancellables/ct","version":"2.2.1","description":"CancellationToken class","main":"index.js","type":"module","repository":{"type":"git","url":"git+https://github.com/vuwuv/async-cancellables.git","directory":"packages/ct"},"keywords":["async","cancellable","CancellationToken","cancellation"],"author":{"name":"vuwuv"},"license":"MIT","bugs":{"url":"https://github.com/vuwuv/async-cancellables/issues"},"homepage":"https://github.com/vuwuv/async-cancellables#readme","engines":{"node":">=18.0.0"},"gitHead":"ef6aca6697cdb8939554b8309935734d0e37806b","_id":"@async-cancellables/ct@2.2.1","_nodeVersion":"18.15.0","_npmVersion":"9.3.1","dist":{"integrity":"sha512-Hu6EhqTFdCiUvqKp/7gskb3IUOED3vv5JbBN/YvobcXwwqFTkWeGGyeqhwNoRkEd3JHgag2v8Y8tMauzdoLKXg==","shasum":"b9d81e8f40cadbc188aa40f760d5aa9436923234","tarball":"https://registry.npmjs.org/@async-cancellables/ct/-/ct-2.2.1.tgz","fileCount":5,"unpackedSize":32679,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCICzblZxlfoxLBm17C0gDxQB3y53987A6uMvkyVrPPOcxAiAX0Ry7wocSLszujjGv0SbKL1hiX1Ua/TLj5xe1QiWy/A=="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJkFaZNACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2Vmo9aBAAn4DOibf0OntlxrrxhxH02DAliGmyn3a55O7AZuqwpA1ysZ5B\r\nKzlV7LPtbbyQp7o7dxyroz9lZnIqywLGe11i9Mku1McKtWas1Ui9DtKYKMHL\r\nf5DkvZgmypfj+7O/sd6iKIIGQMoIV7jC1rBNQMYk11gvxKsLE8GXpPdi2V8+\r\naMjKJnAA84eaENV/8DqqxV6xyeHEBh43UXtEvXjvqnM6YuoDfLXRfo2YAK/y\r\nQE8Trz++AMpkQEDLJLzNVLxzNUDxvPo7eEFtIJHuNaDx+qKPABJZIgusXi1G\r\nqavSe7lLQBx5HMIa2MdhNfX4uoHYCUXuREERrs7Y1d+1OgmYXlOlI/Z0VZQs\r\ntRys4eUvWEBetYYr9l1p+kG61BW11IOh5RqsBtnIjmZRCESnyH3+EB/N26S/\r\nR8chvbfyzYWNBiVfQVLvjS/UzlznpAK2ZxbXB9Vtg2C/8iJ/zurHRHt5kFGd\r\n+GrQjz7XFgUTwY9uclK+7gHJq1Tj7UV+IJOfaVk0DluWvx55rUmdrPK8r742\r\n1+3NlGxwdxve6aVps8TP3zQu3W5Z6MnFFHSZghRlOQG9vdKneboB6kmmCo0k\r\nXDj9KUzFDJObAigs9FBlbYhAFfvsfA0HjKPrCJbGivxCfAQDBq6WkDYqTPhv\r\nf3NrMpdZNtdDhJ2sSwWoRKW9nIUmkWqWf4E=\r\n=efTu\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"vuwuv","email":"vkhubb@gmail.com"},"directories":{},"maintainers":[{"name":"vuwuv","email":"vkhubb@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ct_2.2.1_1679140428890_0.4118878559882013"},"_hasShrinkwrap":false},"2.3.0":{"name":"@async-cancellables/ct","version":"2.3.0","description":"CancellationToken class","main":"index.js","type":"module","repository":{"type":"git","url":"git+https://github.com/vuwuv/async-cancellables.git","directory":"packages/ct"},"keywords":["async","cancellable","CancellationToken","cancellation"],"author":{"name":"vuwuv"},"license":"MIT","bugs":{"url":"https://github.com/vuwuv/async-cancellables/issues"},"homepage":"https://github.com/vuwuv/async-cancellables#readme","engines":{"node":">=18.0.0"},"gitHead":"a85312106999493278409fdf9c14455f42cfbcf3","_id":"@async-cancellables/ct@2.3.0","_nodeVersion":"18.15.0","_npmVersion":"9.3.1","dist":{"integrity":"sha512-tJ8MP7z1sIyC9y0w1d4KKndUfXupaswHpNr/HVkAFFijoTJbrpkrU4U60cMTr26z1zEUsKsjgQ5eKvPOmDlYmQ==","shasum":"34066b35c33805181aa1eb67993a71025bf69b47","tarball":"https://registry.npmjs.org/@async-cancellables/ct/-/ct-2.3.0.tgz","fileCount":5,"unpackedSize":37223,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIC4AMaDcETIzurdG5trKRIbootR5BiCMe4xnSccn/b0NAiB8bb2HWP76Dw+Cd2bcRXe0uSAUFkhN6+AHiSghx5VIvw=="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJkJdSCACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmoIcA/+LzgokHl7nXuy/ygLrnzAEKWpjLCaJa2mFeCJP2IVtqLEX0n3\r\nwKHKq+4L2yIhL6UPiMCPkJEWsN5mDBLrMpk8QXWnmW7oN0zZ2NSfxBXsm69u\r\nA4bEWrh3/9CCJTYvNPQhSyow0NTKf/PNU4DWVvCmVUTXmu9q//bhNcTXev0+\r\nsGPqjbCacZRLfdRrJjyiatXj6Q9wxqWTe+rhE6cX1jJNkbBMyuQiNrCqtlFy\r\nFxR3vXsFxE+geosSNGO0ijbIbq5KTyu2MJ5Qr1Y4o/mamleoqD0IDhHCA/Qt\r\nQSQYMYZsX9gCxhyklyqu56w8AfqgtKV1MLFk1msDiXg9bTHn+bZ1r/pkI2i1\r\nKh62110idsJPHOuFGFhwSK2y+UzlPVa8JNXYA/U3CrnstF0aTCY0QxzvYvn/\r\ngAzQubv/s96ipxc84ZpELRl5l4dzKX/z3V6z8SmgOej6dE5ajKIEQUyOHN4I\r\n2ReQQB0HzE8+gZhSgzILzTROaGVOEjpjP1RJjVfPGESZEA/ER5abBrXwVWBO\r\nBJjt1IdLB6h+TuDyq1tSxtoSRQuEfSGq15vMyzm1mc0bayqJYaNhIlI+fhVQ\r\nfJDZNsExNCGt5jLXFSW8SZKTnVMhgciBBU1H+4Zqrw6PngGl1iGRqGFuxOML\r\nlC2tNfA7TldVwfdbdZYyygkG3YvaLWaSz/0=\r\n=0oIV\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"vuwuv","email":"vkhubb@gmail.com"},"directories":{},"maintainers":[{"name":"vuwuv","email":"vkhubb@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ct_2.3.0_1680200834468_0.5656214629075664"},"_hasShrinkwrap":false}},"time":{"created":"2023-03-05T09:44:18.687Z","2.0.0":"2023-03-05T09:44:18.890Z","modified":"2023-03-30T18:27:14.977Z","2.1.0":"2023-03-07T20:59:33.659Z","2.2.0":"2023-03-15T15:11:13.079Z","2.2.1":"2023-03-18T11:53:49.133Z","2.3.0":"2023-03-30T18:27:14.864Z"},"maintainers":[{"name":"vuwuv","email":"vkhubb@gmail.com"}],"description":"CancellationToken class","homepage":"https://github.com/vuwuv/async-cancellables#readme","keywords":["async","cancellable","CancellationToken","cancellation"],"repository":{"type":"git","url":"git+https://github.com/vuwuv/async-cancellables.git","directory":"packages/ct"},"author":{"name":"vuwuv"},"bugs":{"url":"https://github.com/vuwuv/async-cancellables/issues"},"license":"MIT","readme":"# Async Cancellables / CancellationToken\n\n> CancellationToken class allows to organize asynchronous operations cancellation\n\n## Table of contents\n\n-   [Prerequisites](#prerequisites)\n-   [Table of contents](#table-of-contents)\n-   [Installation](#installation)\n-   [Examples](#examples)\n    -   [Basic usage](#basic-usage)\n    -   [Using improved race/any methods](#using-improved-raceany-methods)\n    -   [File download function limiting concurrent downloads](#file-download-function-limiting-concurrent-downloads)\n    -   [Cancellable async calls via socket](#cancellable-async-calls-via-socket)\n    -   [Cancellable sleep promise](#cancellable-sleep-promise)\n-   [Debug mode](#debug-mode)\n-   [API](#api)\n    -   [Creating tokens](#creating-tokens)\n    -   [Token names](#token-names)\n    -   [Wait methods](#wait-methods)\n    -   [Static wait methods](#static-wait-methods)\n    -   [Cancel methods](#cancel-methods)\n    -   [Properties](#properties)\n    -   [Utility methods](#utility-methods)\n    -   [Static utility methods](#static-utility-methods)\n    -   [Race methods](#race-methods)\n    -   [Events](#events)\n-   [Authors](#authors)\n-   [License](#license)\n\n## Prerequisites\n\nThis project requires NodeJS (version 18 or later) and NPM.\n\n## Installation\n\nTo install and set up the package, run:\n\n```sh\n$ npm install @async-cancellables/ct\n```\n\n## Examples\n\n### Basic usage\n\nCreating independent cancellation tokens:\n\n```js\n// cancelled manually by calling parent1.cancel()\nconst parent1 = CT.manual();\n\n// cancelled after 5 seconds\nconst parent2 = CT.timeout(5000);\n\n// cancelled when 'event' event is emitted on target\nconst parent3 = CT.event(target, 'event');\n```\n\nCreating child cancellation tokens:\n\n```js\n// cancelled after 10 seconds or when parent1 is cancelled (manually)\nconst child1 = parent1.timeout(10000);\n\n// cancelled when 'event' event is emitted on target or when parent2 is cancelled (after 5 seconds)\nconst child2 = parent2.event(target, 'event');\n\n// cancelled manually by calling child3.cancel() or when parent3 is cancelled (when 'event' event is emitted on target)\nconst child3 = parent3.manual();\n```\n\nUsing tokens:\n\n```js\nconst token = CT.manual();\n\n// waits for asyncCall() to finish, but throws an error if token is cancelled\nconst asyncCallResult = await token.waitPromise(asyncCall());\n\n// waits for target.event event to be emitted, but throws an error if token is cancelled, returns array of event arguments\nconst eventArgumentsArray = await token.waitEvent(target, 'event');\n\n// waits for 10 seconds, but throws an error if token is cancelled\nawait token.sleep(10000);\n```\n\n### Using improved race/any methods\n\n```js\n// every lock imitates remote resource\nconst locks = [new AsyncLock(1), new AsyncLock(1), new AsyncLock(1)];\n\n// waits for the first lock to be available, cancels waiting for other locks\nconst waitSuccess = await CT.any(locks.map((lock) => lock.waitOne()));\n\n// it's possible to wait with a timeout\nconst waitSuccess = await CT.timeout(5000).any(locks.map((lock) => lock.waitOne()));\n\n// waitSuccess contains index of the lock and the ticket\nconst index = waitSuccess.index;\nconst ticket = waitSuccess.value;\n```\n\n### File download function limiting concurrent downloads\n\n```js\nconst asyncLock = new AsyncLock(5);\n\nasync function downloadFile(url, ct = null) {\n    const ticket = await asyncLock.waitOne(ct);\n    try {\n        return await ct.waitPromise(got(url));\n    } finally {\n        ticket.release();\n    }\n}\n\nconst content = await downloadFile('https://example.com/', CT.timeout(5000));\n```\n\nDownloads file from `url` with 5 concurrent downloads. If it takes more than 5 seconds, and the function still waits for a slot, it will exit the queue and throw an error. If it is already downloading, the function will throw an error immediately, but actual download will continue in the background. `asyncLock.waitOne` call supports cancellation, so if `ct` is cancelled, the function will exit the queue.\n\n### Cancellable async calls via socket\n\n```js\nsocket.on('connection', (client) => {\n    const clientCT = CT.event(client, 'disconnect');\n\n    client.on('startProcessing', (...args) => {\n        const key = randomKey();\n        const requestCT = CT.event(client, `cancelProcessing_${key}`).attachTo(clientCT);\n        processing(requestCT, ...args).then(\n            (result) => client.emit(`finishProcessing_${key}`, result),\n            (error) => !CT.isCancellationError(error) && console.log(error)\n        );\n    });\n});\n```\n\nSocket processes async calls of `processing()` function. If client disconnects, all pending calls are cancelled. If client sends `cancelProcessing_${key}` event, the call with the same key is cancelled. `clientCT` is getting cancelled when client disconnects, it is created once per connection. `requestCT` is getting cancelled when client disconnects or sends `cancelProcessing_${key}` event, it is created once per call and attached to `clientCT` to cancel all calls when client disconnects.\n\n### Cancellable sleep promise\n\n```js\nasync function sleep(ms, ct = null) {\n    return new Promise((resolve, reject) => {\n        let timeout;\n        if (ct) {\n            ct.throwIfCancelled();\n            [resolve, reject] = ct.processCancel(resolve, reject, clearTimeout.bind(null, timeout));\n        }\n        timeout = setTimeout(resolve, ms);\n    });\n}\n```\n\nExample of binding cancellation token to a promise. If `ct` is cancelled, the promise will be rejected with `ct` error. If `ct` is not cancelled, the promise will be resolved after `ms` milliseconds. `ct.throwIfCancelled()` checks if `ct` is already cancelled and throws an error if it is. `ct.processCancel()` returns a new `resolve` and `reject` functions that will prevent calling cancel function (in this case it is `clearTimeout.bind(null, timeout)`) after promise is resolved or rejected. On cancelling `ct`, `onCancel` function will be called, it should stop the operation that is being waited for. In this case, it is clearing existing timeout.\n\n## Debug mode\n\nTo enable debug mode, set `CT_DEBUG` environment variable to any value.\nIn production mode tokens use error-like objects with stack traces, but in debug mode they use full Error objects which have both call stack (call that has been cancelled by the token) and cancellation stack (calls that caused the token to be cancelled).\n\n## API\n\n### Creating tokens\n\nThere are 3 types of cancellation tokens:\n\n-   `manual` token can be cancelled only manually\n-   `timeout` token cancels after specified amount of time passes\n-   `event` token cancels after specified event on target object is fired, can safely listen to persistent objects as it listens using weak reference\n\nThey can be created using static methods:\n\n-   `CancellationToken.manual(options = null)`\n-   `CancellationToken.timeout(ms, options = null)`\n-   `CancellationToken.event(target, eventName, options = null)`\n\nor by creating direct children for any token instance (same parameters apply):\n\n-   `token.manual(options = null)`\n-   `token.timeout(ms, options = null)`\n-   `token.event(target, eventName, options = null)`\n\nOptions can be:\n\n-   `parents` - array of parents which can contain `null` or duplicate values that are ignored for convenience reasons\n-   `name` - string or symbol name of the token, used for debugging or analysis purposes and also used for error messages and markers\n-   `createError` - function that creates error object when token is cancelled instead of default `CancellationTokenError`\n-   `options` - options object containing `name`, `parents`, `createError`\n\nYou can also add/remove additional parents to existing tokens via `attachTo` and `detachFrom` methods\n\n-   `token.attachTo(...parents)` adds parents ignoring duplicate and `null` parents and returns `this`\n-   `token.detachFrom(...parents)` removes parents ignoring non-existent and `null` parents and returns `this`\n\nToken is also cancelled when any of it's direct or indirect parents cancels. If a token chain is attached to a cancelled parent the whole chain immediately cancels.\n\nTokens can be cancelled ONLY ONCE!\n\n### Token names\n\nToken has a `name` property that can be used not only for debugging or analysis purposes, but also for using as markers for error objects. It is `undefined` by default, but can be set upon creation. \n\nToken name as a string value or symbol description is used in error messages, while name value can be accessed via `error.marker` property. \n\n```js\nconst timedOut = Symbol('timed out');\nconst token = CancellationToken.timeout(1000, timedOut);\n\ntry {\n    await dbCall(token);\n} catch (error) {\n    if (error.marker === timedOut) {\n        // timed out\n    }\n}\n```\n\n### Wait methods\n\nToken has several asynchronous wait methods. Each of them returns when token cancels or method task is done. Method can also throw on cancel if the corresponding option is used. `doNotThrow` parameter is optional, if it is `true` method returns token that cancelled instead of throwing error.\n\n-   `wait(promise, doNotThrow = false)` waits for the promise to resolve and returns promise result if does not cancel\n-   `waitEvent(target, eventName, doNotThrow = false)` waits for the `eventName` on the `target` to fire and returns the array of event arguments if does not cancel\n-   `handleEvent(target, eventName, handler, doNotThrow = false)` waits for the `eventName` on the `target` to fire and returns the result of the `handler` function called with the array of event arguments if does not cancel\n-   `sleep(ms, successValue, doNotThrow = false)` waits for the specified amount of milliseconds to pass and returns `successValue` if does not cancel\n\n### Static wait methods\n\nCancellationToken token has the same static wait methods, except they have additional first parameter `cancellationToken` which can be `null` or CancellationToken instance. If it is `null` wait method is executed without any cancellation.\n\n-   `CancellationToken.wait(promise, cancellationToken = null, doNotThrow = false)`\n-   `CancellationToken.waitEvent(target, eventName, cancellationToken = null, doNotThrow = false)`\n-   `CancellationToken.handleEvent(target, eventName, handler, cancellationToken = null, doNotThrow = false)`\n-   `CancellationToken.sleep(ms, successValue, cancellationToken = null, doNotThrow = false)`\n\n### Cancel methods\n\n-   `cancel()` cancels any (not just manual) token immediately and returns `this`\n\n### Properties\n\n-   `name` returns token name or `null` if not specified\n-   `cancelled` returns `true` if token is cancelled\n-   `cancelledBy` if cancelled returns token that cancelled, `null` otherwise\n-   `cancelledError` returns error object that was used to cancel token or `null` if token is not cancelled\n-   `isManual` returns `true` if token has `manual` type\n-   `isTimeout` returns `true` if token has `timeout` type\n-   `isEvent` returns `true` if token has `event` type\n-   `isCancellationToken` always returns `true`\n\n### Utility methods\n\n-   `isToken(object)` checks if the `object` is a cancellation token\n-   `throwIfCancelled()` if cancelled throws cancel error\n-   `catchCancelError(promise)` awaits the promise and returns it's result, if cancel error is thrown returns cancelled token, rethrows any other error\n-   `processCancel(resolve, reject, cancel, doNotThrow = false)` when token is cancelled calls `cancel` and then `resolve` or `reject` depending on `doNotThrow` value and returns array of rewritten `resolve` and `reject` functions to be used\n\n### Static utility methods\n\n-   `CancellationToken.isToken(object)` same as non-static method\n-   `CancellationToken.isCancellationError(error)` checks if the `error` is a `CancellationEventError`\n-   `CancellationToken.catchCancelError(promise)` same as non-static method\n\n### Race methods\n\nBoth methods require generator function `promiseListGenerator(token)`: it should use `token` to create async calls and return promise list\n\n`race(promiseListGenerator, doNotThrow = false)` uses `promiseListGenerator` to get a promise list, waits for any promise to resolve/reject or for the current token to cancel, then cancels `token` (which is direct descendant of the current token) to stop execution of the rest of the async calls\n\nAll possible execution scenarios depeding on `doNotThrow` value, async calls results and current token state:\n\n-   `doNotThrow` is `false` and current token cancels before any of the promises resolves or rejects - `CancellationEventError` is thrown\n-   `doNotThrow` is `true` and current token cancels before any of the promises resolves or rejects - cancelled token is returned\n-   one of the promises resolves before any other events - `RaceSuccess` object is returned containing `index` and `value` of the resolved promise\n-   one of the promises rejects before any other events - `RaceError` is thrown containing `index` and `result` of the rejected promise\n\n`any(promiseListGenerator, doNotThrow = false)` uses `promiseListGenerator` to get a promise list, waits for any promise to resolve, all promises to reject or for the current token to cancel, then cancels `token` (which is a direct descendant of the current token) to stop execution of the rest of the async calls\n\nAll possible execution scenarios depeding on `doNotThrow` value, async calls results and current token state:\n\n-   `doNotThrow` is `false` and current token cancels before any of the promises resolves or rejects - `CancellationEventError` is thrown\n-   `doNotThrow` is `true` and current token cancels before any of the promises resolves or rejects - cancelled token is returned\n-   one of the promises resolves before current token cancellation - `RaceSuccess` object is returned containing `index` and `value` of the resolved promise\n-   all the promises reject before current token cancellation - `AggregateError` is thrown containing error list\n\n### Static race methods\n\n`CancellationToken.race(promiseListGenerator, doNotThrow = false)`\n`CancellationToken.any(promiseListGenerator, doNotThrow = false)`\n\nStatic function have similar logic as non-static ones, but don't support cancellation and can be used without creating a token.\n\n### Events\n\n-   `cancel` fires on token cancel and gets cancelled token as an argument\n\n## Authors\n\n-   **vuwuv** - _Initial work_ - [vuwuv](https://github.com/vuwuv)\n\n## License\n\n[MIT License] © vuwuv\n","readmeFilename":"README.md"}