3 ms·
You can technically achieve this from callbacks as well. Simply pass in the callback as a function to the method. This way you can still make your async call in
by RyanZAG 13y ago
You can technically achieve this from callbacks as well. Simply pass in the callback as a function to the method. This way you can still make your async call in a context where you don't know what has to be done next - what will be done next can be passed in dynamically to the function.
That said, I still much prefer promises as they make it much more explicit.
- sanderjd 13y agoI'm confused by your comment. > Simply pass in the callback as a function to the method. This way you can still make your async call in a context where you don't know what has to be done next - what will be done next can be passed in dynamically to the function. That sounds like you're just describing how callbacks work in general... The point is that you have to know what function to pass in at the time you make the asynchronous call. With promises, you can figure that out later.
- MBlume 13y agoLet'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.
- robmcm 13y agoThere is a slight limitation where you async operation returns before you assign your call back. By using an object (in this case a promise) you could cache the result and make it available to anyone adding a listener in the future.