|Written by Mike James|
|Tuesday, 30 April 2013|
It all seems to work but it needs ES6 and support for generators which means at the moment it only works in Firefox.
The latest idea is to make use of generator functions and the new yield command. This allows a function to return a result to its caller much like a return. The difference is that the calling function can make the function resume from where it left off - its a limited form of a continuation.
The new framework implements a scheduler and uses the yield command to allow a function wrapped as a task to suspend its execution until some asynchronous action is completed. The main restriction is that the action called as part of the yield command has to return a Promise object. For example most jQuery asynchronous methods have at least an option to return a Promise or a Deferred object.
So what happens is the task that want to wait on an asynchronous call that returns a value simply uses:
The yield returns control to the scheduler along with the promise object returned by myAsynchMethod. The scheduler then either runs another task or returns its thread to process events for the UI. When myAsynchMethod is finished it resolves the promise and calls onResolve with the value that is its result. This wakes the scheduler up, again, and it takes the value and uses the send(value) command to resume the original task at the yield. This results in the value, and not the promise, being stored in result.
Notice that as far as the programmer making use of the framework and the asynchronous method is concerned, there is no need to know anything about promises or how everything works. If you have an asynchronous method then you can call it in what appears to be a synchronous way by simply calling it with yield.
As the task.js website puts it:
generators + promises = tasks
You can see a full example at the task.js website:
There are lots of fine details about how task.js works and it is a fascinating and very clever re-purposing of a feature added to ES6. After all, the real purpose of the yield is to make writing iterators easy and not to allow a asynchronous action to yield control to a calling function.
Will task.js catch on?
The first hurdle it has to negotiate is that ES6 has to be supported by all browsers and all, or at least the majority of, asynchronous operations need to return promises. Both of these conditions will need some time before they become true.
No matter what the future holds, task.js is well worth looking at if only to understand how it works.
To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, Facebook, Google+ or Linkedin, or sign up for our weekly newsletter.
or email your comment to: email@example.com
|Last Updated ( Monday, 06 May 2013 )|