index.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*!
  2. * deasync
  3. * https://github.com/abbr/deasync
  4. *
  5. * Copyright 2014-present Abbr
  6. * Released under the MIT license
  7. */
  8. var fs = require('fs'),
  9. path = require('path'),
  10. binding
  11. // Seed random numbers [gh-82] if on Windows. See https://github.com/laverdet/node-fibers/issues/82
  12. if (process.platform === 'win32') Math.random()
  13. // Look for binary for this platform
  14. var nodeV = 'node-' + /[0-9]+\.[0-9]+/.exec(process.versions.node)[0]
  15. var nodeVM = 'node-' + /[0-9]+/.exec(process.versions.node)[0]
  16. var modPath = path.join(__dirname, 'bin', process.platform + '-' + process.arch + '-' + nodeV, 'deasync')
  17. try {
  18. try {
  19. fs.statSync(modPath + '.node')
  20. } catch (ex) {
  21. modPath = path.join(__dirname, 'bin', process.platform + '-' + process.arch + '-' + nodeVM, 'deasync')
  22. fs.statSync(modPath + '.node')
  23. }
  24. binding = require(modPath)
  25. } catch (ex) {
  26. binding = require('bindings')('deasync')
  27. }
  28. function deasync(fn) {
  29. return function () {
  30. var done = false
  31. var args = Array.prototype.slice.apply(arguments).concat(cb)
  32. var err
  33. var res
  34. fn.apply(this, args)
  35. module.exports.loopWhile(function () {
  36. return !done
  37. })
  38. if (err)
  39. throw err
  40. return res
  41. function cb(e, r) {
  42. err = e
  43. res = r
  44. done = true
  45. }
  46. }
  47. }
  48. module.exports = deasync
  49. module.exports.sleep = deasync(function (timeout, done) {
  50. setTimeout(done, timeout)
  51. })
  52. module.exports.runLoopOnce = function () {
  53. process._tickCallback()
  54. binding.run()
  55. }
  56. module.exports.loopWhile = function (pred) {
  57. while (pred()) {
  58. process._tickCallback()
  59. if (pred()) binding.run()
  60. }
  61. }