3 ms·
Let's say I'm in the middle of the method foo, and I do some asynchronous operation. With a promise, I can do two things, I can pass it into some other functio
by MBlume 13y ago
Let's say I'm in the middle of the method foo, and I do some asynchronous operation.
With a promise, I can do two things, I can pass it into some other function, or I can return it to the caller of foo
with a callback, I can do two things, I can supply a callback which passes the result into some function, or I can require that the caller of foo provide a callback, which I pass along to the asynchronous operation I'm calling
these seem roughly isomorphic to me -- I guess a difference is that if I pass the promise to a method I'm allowing the method to decide when to deref it, but that seems different from the "tightly coupled" claim.
- skybrian 13y agoIt's a matter of timing. A callback function could be called immediately and you need to be ready for that, so you need to define the callback before passing it in. With a promise, you can call the then() method after the function returns; if the value is ready earlier then it will automatically be cached until you pick it up. The looser requirements on timing result in better decoupling; like any other value, you can put the promise in an arbitrary data structure and pick it up any time later, or perhaps not at all. If you want to do this with callbacks you'll need to implement a way to cache the value and the result will be equivalent to a promise.
- sanderjd 13y agoReturning a promise to the caller and requiring the caller to pass in a callback are not isomorphic. If you return a value to me, I can figure out what to do with it whenever I want. If you make me pass you a callback, I have to know what I want to do, right when I call you.