Skip to content

Instantly share code, notes, and snippets.

@jordaaash
Last active August 31, 2017 18:57
Show Gist options
  • Save jordaaash/ead1091cb6c0b5a9d871b2a9b741eaf6 to your computer and use it in GitHub Desktop.
Save jordaaash/ead1091cb6c0b5a9d871b2a9b741eaf6 to your computer and use it in GitHub Desktop.
Promise + Fiber
/* @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;
@jordaaash
Copy link
Author

jordaaash commented Aug 31, 2017

await fiber(function (next) {
    next(); // pause
    next(); // resume
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment