Last active
April 24, 2017 02:44
-
-
Save JLChnToZ/5bffdca7b4190e3837a4e55bd3cc4fdd to your computer and use it in GitHub Desktop.
Add support for promises with Node Sync.
This file contains hidden or 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
| // Add support for promises with Node Sync. | |
| // https://github.com/ybogdanov/node-sync | |
| (function() { | |
| 'use strict'; | |
| const { Fibers, Future } = module.exports = require('sync'); | |
| const slice = Function.prototype.call.bind(Array.prototype.slice); | |
| if(typeof Promise !== 'undefined') { | |
| // Pause execution and wait until the promise fufilled. | |
| Promise.prototype.sync = function() { | |
| const fiber = Fibers.current; | |
| let err, result, yielded, called; | |
| this.then(function(value) { | |
| if(called) return; | |
| called = true; | |
| result = arguments.length > 1 ? | |
| slice(arguments) : value; | |
| if(yielded) fiber.run(); | |
| }, function(reason) { | |
| if(called) return; | |
| called = true; | |
| err = reason; | |
| if(yielded) fiber.run(); | |
| }); | |
| if(!called) { | |
| yielded = true; | |
| Fibers.yield(); | |
| } | |
| if(err) throw err; | |
| return result; | |
| }; | |
| // Converts a promise to future. | |
| Promise.prototype.toFuture = function() { | |
| const future = new Future(); | |
| this.then(function() { | |
| const args = slice(arguments); | |
| args.unshift(null); | |
| future.apply(null, args); | |
| }, future); | |
| return future; | |
| }; | |
| } | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment