0

Example using callback :

Parse.User.logIn("user", "pass", {
 success: function(user) {
  query.find({
   success: function(results) {
    results[0].save({ key: value }, {
     success: function(result) {
      // the object was saved.
     }
    });
   }
  });
 }
});

Example using promise :

Parse.User.logIn("user", "pass").then(function(user) {
  return query.find();

}).then(function(results) {
  return results[0].save({ key: value });

}).then(function(result) {
  // the object was saved.
});

Is promise used only for code readability or is there any other performance impact on the execution of code because both are doing the same thing.

Rohit
  • 2,987
  • 3
  • 25
  • 50
  • Well for one thing you can pass Promises around and execute a `.then()` on it long after it has been resolved or rejected. Can't do that with callbacks. – idbehold May 09 '15 at 05:32
  • We can pass function(err, data) as callbacks, so where is the difference, is there any performance issue with callbacks ? Please let me know any clear example for promise. – Rohit May 09 '15 at 05:41
  • @idbehold: You can do that with some implementation of promises (like the one I wrote myself) but in general almost all promise implementation don't support this feature. This is called synchronous promises - where the promise may resolve before you call `.then()` (thereby allowing synchronous code such as .forEach() to use promises). Almost none of the popular promise libraries can do this. And the ES6 promises that is/will be built-in to javascript can't do this. You must call `then()` before the promises are resolved. – slebetman May 09 '15 at 10:22
  • @slebetman I said nothing about being able to do anything synchronously or inside a forEach loop. I simply said you could pass the Promise around and call `.then()` on it. And you definitely can call `.then()` on a Promise that has already been resolved. `Promise.resolve("see, told you").then(console.log.bind(console))` – idbehold May 09 '15 at 12:24
  • @idbehold: By definition, a promise that can be processed after being resolved can be used synchronously (as your example shows). Not all promises can do this though. The promise/a specification explicitly says that resolve must be called in the next tick (that is, after then is called). – slebetman May 09 '15 at 12:35
  • @slebatman you are absolutely wrong that the function passed to `.then()` happens synchronously. In my example it can definitely be processed on the next tick and still work just fine, as it does in pretty much every promise implementation including the native one. `Promise.resolve().then(function(){ console.log('happens on next tick') }); console.log('happens first');` – idbehold May 09 '15 at 12:39

0 Answers0