JQuery 1.5 promises a better future.
renesd.blogspot.com
renesd.blogspot.com
Can anyone explain the difference between promises and futures? I've always used the terms interchangeably.
In practise, this means that futures are best used for multi-threaded calculations, whilst promises are best used for handling events from I/O or some other unpredictable source.
For example, we can assign a promise to get a key-press:
var keyCode = promise();
document.onKeyPress(function(event) {
keyCode.deliver(event.keyCode);
}
But if we tried to use a future, we'd have to do something like: var keyCode = future(function() {
while (true) {
var event = waitForEvent();
if (event.type == "keypress") return event.keyCode;
}
}
The future is essentially wasting a thread waiting for input, whilst the promise is inert until a keypress occurs.For example, in Python it's:
executor = ThreadPoolExecutor(max_workers=1)
x = executor.submit(func, arg1, arg2)
print x.result()
In Clojure it's: (let [x (future (func arg1 arg2))]
(println @x))
In Java: ExecutorService executor = Executors.newFixedThreadPool(1);
FutureTask<String> x =
new FutureTask<String>(new Callable<String>() {
public String call() {
return SomeClass.func(arg1 arg2);
}});
executor.execute(x);
System.out.println(x.get());
Basically the same idea; execute some code in a background thread and return the result when asked. If the result isn't ready, then block.Apparently some languages use a callback to get the result, rather than blocking, but the most common approach I've seen is just to block the thread until the future is finished.