10

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?

Chad
  • 1,750
  • 2
  • 16
  • 32
user3420180
  • 254
  • 2
  • 9
  • 2
    It's all about callbacks and Promises. It allows you to run async code synchronously. – Molda Apr 15 '16 at 06:30

1 Answers1

11

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;
  }
});
ko0stik
  • 628
  • 5
  • 14
  • I have had problems with 'throw', seeing a message "Future resolved more than once". I think that with future.throw although callbacks are resolved it does not halt execution. See here: https://www.npmjs.com/package/fibers. A structure like "if (error) future.throw(error) else future.return(result)" should be safer. – Little Brain Mar 19 '19 at 13:46
  • I am not sure, but I think future.return also does not halt exceution. – Little Brain May 15 '20 at 09:17
  • You need to make sure that your future only throws and returns once. The best was to do this is to always `return future.throw()` as the throw()/ return() itself does not end the execution. – Tobi May 27 '21 at 11:25