Last active
August 31, 2017 18:57
-
-
Save jordaaash/ead1091cb6c0b5a9d871b2a9b741eaf6 to your computer and use it in GitHub Desktop.
Promise + Fiber
This file contains 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
/* @flow */ | |
'use strict'; | |
const Promise = require('bluebird'); | |
const Fiber = require('fibers'); | |
const fiber = function <T: any> (callback: () => T): Promise<T> { | |
return new Promise(function (resolve: Function, reject: Function): void { | |
Fiber(function (): void { | |
let fiber: Fiber = Fiber.current; | |
let yielded: boolean = false; | |
let value: T; | |
try { | |
value = callback(function next (): void { | |
if (yielded) { | |
yielded = false; | |
fiber.run(); | |
} | |
else { | |
yielded = true; | |
Fiber.yield(); | |
} | |
}); | |
if (yielded) { | |
resolve(value); | |
} | |
else { | |
throw new Error('fiber not yielded'); | |
} | |
} | |
catch (error) { | |
reject(error); | |
} | |
finally { | |
fiber = null; | |
} | |
}).run(); | |
}); | |
}; | |
module.exports = fiber; |
Author
jordaaash
commented
Aug 31, 2017
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment