Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do fibers/future actually do?

What does the line of code below do?

Npm.require('fibers/future');

I looked online for examples and I came across a few like this:

Future = Npm.require('fibers/future');
var accessToken = new Future();

What will accessToken variable be in this case?

like image 420
user3420180 Avatar asked Apr 15 '16 03:04

user3420180


1 Answers

Question is a bit old but my 2 cents:

As Molda said in the comment, Future's main purpose is to make async things work synchronously. future instance comes with 3 methods:

  • future.wait() basically tells your thread to basically pause until told to resume.
  • future.return(value), first way to tell waiting future he can resume, it's also very useful since it returns a value wait can then be assigned with, hence lines like const ret = future.wait() where ret becomes your returned value once resumed.
  • future.throw(error), quite explicit too, makes your blocking line throw with given error.

Making things synchronous in javascript might sound a bit disturbing but it is sometimes useful. In Meteor, it's quite useful when you are chaining async calls in a Meteor.method and you want its result to be returned to the client. You could also use Promises which are now fully supported by Meteor too, I've used both and it works, it's up to your liking.

A quick example:

Meteor.methods({
  foo: function() {
    const future = new Future();
    someAsyncCall(foo, function bar(error, result) {
      if (error) future.throw(error);
      future.return(result);
    });
    // Execution is paused until callback arrives
    const ret = future.wait(); // Wait on future not Future
    return ret;
  }
});
like image 110
ko0stik Avatar answered Sep 22 '22 10:09

ko0stik