3

In the following piece of code the fiber works as expected ("1" and "2" are printed 2 seconds apart). But, I want to return "3" from fiberFunction and print that synchronously. This doesn't work though.Here is the output:

1
Temp: undefined
2

Does anybody know how to return a value from a fiber function?

var Fiber = require('fibers');
var Future = require('fibers/future'), wait = Future.wait;

function sleep(ms) {
    var future = new Future;
    setTimeout(function() {
        future.return();
    }, ms);
    return future;
}

var fiberFunction = Fiber(function() {
    console.log("1");
    sleep(2000).wait();
    console.log("2");
    return "3";
});

var fiberReturn = fiberFunction.run();
console.log("Temp: " + fiberReturn);
Artjom B.
  • 61,146
  • 24
  • 125
  • 222

1 Answers1

0

So your problem is that fiberFunction is not a function, it is a fiber instance, and fiber instances don't return anything. Also, you should not use Future.wait directly — you should only wait on instances.

You should instead be doing this:

var Fiber = require('fibers')
var Future = require('fibers/future')

function sleep(ms) {
    var future = new Future
    setTimeout(function() {
        future.return()
    }, ms)
    return future
}

var yourFunction = function() {
    console.log("1")
    sleep(2000).wait()
    console.log("2")
    return "3"
}

Fiber(function() {   
    console.log("Temp: " + yourFunction())
}).run()

I'd recommend you read the README documentation thoroughly before using Fibers or futures in earnest.


This was copied from node-fibers issue #171 because many people end up here instead. Originally written by fresheneesz.

Minderov
  • 521
  • 1
  • 5
  • 20