In Mozilla code,
Task.spawn() is becoming a common way to implement asynchronous operations, especially methods like the
greet method in this
greeter object:
let greeter = {
message: "Hello, NAME!",
greet: function(name) {
return Task.spawn((function*() {
return yield sendGreeting(this.message.replace(/NAME/, name));
}).bind(this);
})
};
Task.spawn() makes the operation logic simple, but the wrapper function and
bind() call required to start the task on method invocation and bind its
this reference make the overall implementation complex.
Enter
Task.async().
Like
Task.spawn(), it creates a task, but it doesn't immediately start it. Instead, it returns an "async function" whose invocation starts the task, and the async function binds the task to its own
this reference at invocation time. That makes it simpler to declare the method:
let greeter = {
message: "Hello, NAME!",
greet: Task.async(function*(name) {
return yield sendGreeting(this.message.replace(/NAME/, name));
})
};
With identical semantics:
greeter.greet("Mitchell").then((reply) => { ... }); // behaves the same
(And it avoids a couple anti-patterns in the process.)
Task.async() is inspired by ECMAScript's
Async Functions strawman proposal and
C#'s Async modifier and was implemented in
bug 966182. It isn't limited to use in method declarations, although it's particularly helpful for them.
Use it to implement your next asynchronous operation!
http://mykzilla.blogspot.com/2014/03/simplify-asynchronous-method.html