Wait for future promise / fiber and return it's value
smac89 opened this issue · 1 comments
I think I am still not understanding how these fibers work. To demonstrate the problem I am facing, I took the fibonacci example from the readme and changed it to match what I am trying to do
import Fiber from "fibers";
function Fibonacci(): () => number {
// Create a new fiber which yields sequential Fibonacci numbers
const fiber: Fiber = Fiber(() => {
const curFib = Fiber.current!;
process.nextTick(() => {
curFib.run();
for (let [prev, curr] = [1, 0]; ; [prev, curr] = [curr, prev + curr]) {
Fiber.yield(curr); // This `yield` is problematic
}
});
Fiber.yield();
});
// Return a bound handle to `run` on this fiber
return fiber.run.bind(fiber);
}
const seq = Fibonacci();
for (let ii = seq(); ii <= 1597; ii = seq()) {
console.log(ii);
}
The error I get is:
Error: yield() called with no fiber running
at Function.yield (/home/chigozirim/WebstormProjects/example/node_modules/fibers/fibers.js:90:16)
at process.nextTick (/home/chigozirim/WebstormProjects/example/main.ts:13:28)
at process._tickCallback (internal/process/next_tick.js:61:11)
at Function.Module.runMain (internal/modules/cjs/loader.js:757:11)
at Object.<anonymous> (/home/chigozirim/.nvm/versions/node/v10.15.3/lib/node_modules/ts-node/src/bin.ts:158:12)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
My assumption with fiber is that I can have an async method and as long as I wrap it in a Fiber, I am able to wait for it to finish by calling fiber.run
which will wait for the first call to Fiber.yield
before continuing.
I also tried doing this by wrapping the call in a Future, but calling future.wait
, actually fails because the call needs to wrapped in a Fiber...
How do I actually make async calls, synchronous using Fibers or Futures? This is the main reason why I wanted to use this library in the first place.
process.nextTick
will run at the start of the next tick in a callback and will not be in a fiber.