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?
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;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With