3 ms·
Ugh. There are (at least) two fundamental problems here: First, depsite the ugliness that asynchronous code entails, it does have one very important feature: i
by cwp 12y ago
Ugh. There are (at least) two fundamental problems here:
First, depsite the ugliness that asynchronous code entails, it does have one very
important feature: it never blocks, which makes reasoning about it much easier.
This proposal would make it possible for Javascript code to block, which enables
a whole class of bugs that were impossible before.
var a = future;
var b = future;
setTimeout(function() {
a = b+1;
},0);
setTimeout(function() {
b = a+1;
},0);
console.log(a, b);
Hello deadlocks!
Second, futures aren't first-class values. The proposal specifies that assigning
a future to a variable doesn't create a second reference to the future, it creates
a child future that would be resolve by the resolution of the parent future.
Thus, a future must be resolved in the scope in which it's created, or the
resolution won't be propagated to all its children. With promises, you dont' have
to worry about the side effects of assignment or function calls. Take this
common pattern for wrapping an asynchronous call with a promise:
function promiseMeSomething() {
var d = defer();
doSomethingAsyncronous(function(err, value) {
d.resolve(value);
});
return d.promise;
}
We could do the same with futures:
function futureMeSomething() {
var f = future;
doSomethingAsyncronous(function(err, value) {
f = value;
});
return f;
}
But that callback function is repetitive, so we'll refactor:
function makeCallback(d) {
return function(err, value) {
d.resolve(value);
}
}
function promiseMeSomething() {
var d = defer();
doSomethingAsyncronous(makeCallback(d));
return d.promise;
}
But consider the same refactoring with futures:
function makeCallback(g) {
return function(err, value) {
g = value;
}
}
function futureMeSomething() {
var f = future;
doSomethingAsyncronous(makeCallback(f));
return f;
}
Whoops. This won't work, because g is a child future of
f and resolving it won't resolve f.
- grrowl 12y agoAs well, Javascript's single-threaded execution means blocking execution halts your whole program. IMO, the way to tackle complex asynchronous callback code is with smarter code structure and frameworks — just as you should avoid shoe-horning inheritance OOP into JS, you should write async callback code with readability and flexibility in mind (without complaining you "have to" write bad code)