Make asynchronous functions synchronous
sync-please is a tiny node package that uses fibers to let you call an asynchronous function synchronously. It attempts to minimize the difference between calling a function synchronously and asynchronously, and unlike many other packages, it supports synchronizing nested asynchronous calls.
fibers = require "fibers"makeSynchronous = require "sync-please"# You need to wrap the code you want to run synchronously in a fiber.fibers ->module =:setTimeout callback2000# Asynchronous call.moduleasynchronousFunction"param1""param2"->consolelog "Callback 1"consolelog "Done 1"# Synchronous call.makeSynchronous modulemoduleasynchronousFunction"param1""param2"->consolelog "Callback 2"# Nested synchronous call.makeSynchronous modulemoduleasynchronousFunction"param1""param2"->consolelog "Callback 3"consolelog "Done 2"run
This will output:
Done 1Callback 1Callback 2Callback 3Done 2
There is a small Mocha test suite that you should run if you'd like to contribute to sync-please. Make sure you have Mocha installed and just run
mocha from the root directory.
Copyright (c) 2012 Jarod Long
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.