320 likes | 693 Views
Promises, promise. @ GarrenSmith. “Promises are a software abstraction that makes working with asynchronous operations much more pleasant.” @Dominic http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/. Promises/A+. https:// github.com /promises- aplus /promises-spec.
E N D
Promises, promise... @GarrenSmith
“Promises are a software abstraction that makes working with asynchronous operations much more pleasant.” @Dominic http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/
Promises/A+ https://github.com/promises-aplus/promises-spec
Async is not synchronous! var ping =null; $.get('/ping',function(result){ ping = result; }); console.log(ping) // null;
Promises // jqXHR var promise =backboneModel.save(); promise.then(function(resp){ // do something with saved model }); promise.fail(function(err){ // handle failed error });
Promises // jqXHR var promise =backboneModel.save(); varfinalPromise=promise.then(function(resp){ var promise2 =anotherAsyncMethod(); return promise2; }); finalPromise.then(function(result){ // called once promise 2 completed });
Promises vs. Events myBlogPost.on(‘save’,function(model){ // do something with saved model });
Promises vs. Events // Somewhere else before event declaration myBlogPost.save(); myBlogPost.on(‘save’,function(model){ // do something with saved model });
Promises vs. Events // Somewhere else before event declaration savePromise=myBlogPost.save(); savePromise.done(function(model){ // do something with save promise });
Promises vs. Callbacks doFancyCalculation( input,function(err, result){ if(err){ returnconsole.log('oh no! an error', err); } parseCalulatedResult( result,function(err,parsedResult){ if(err){ returnconsole.log('damn it failed', err); } saveResult(parsedResult,function(err,savedResult){ if(err){ returnconsole.log('could not save', err); } alert('yay, saved'); }); }); });
Promises vs Callbacks doFancyCalculation(input) .then(parseCalulatedResult,handleErr) .then(saveCalculatedResult,handleErr);
Further promise api var promise =myBlog.save(); promise.done(function(){ // called when promise has been resolved }); promise.fail(function(){ // called if promise fails/rejected }); promise.always(function(){ // called when either rejected/resolved });
Further promise api uploadFile() .then(function(){ // Success uploading the file },function(err){ // An error occurred with a reason for error },function(progress){ // Notify of the upload's progress as it is executed });
Serial and Parallel doFancyCalculation(input) .then(parseCalulatedResult,handleErr) .then(saveCalculatedResult,handleErr);
Serial and Parallel var promise1 = asyncOperation1(), promise2 = asyncOperation2(), promise3 = asyncOperation3(); varfinalPromise= $.when(promise1, promise2, promise3); finalPromise.done(function(){ console.log('all async operations finished'); });
Serial and Parallel // unknown number of promises varpromises =comments.map(function(comment){ returncomment.save(); }); $.when.apply(null,promises);
Creating Promises functionasyncMethod(value){ var promise = $.Deferred(); setTimeout(function(){ if(value >100){ promise.resolve(value); }else{ promise.reject('Value is too low.'); } },1000); return promise; };
PipePromises Mixins.SaveQueue={ save:function(attrs,options){ var self =this, save = Backbone.Model.prototype.save; this._queue.then(function(){ returnsave.call(self,attrs, options); }); returnthis._queue; } };
Power of Q https://github.com/kriskowal/q
Interfacing with node.js fs.readFile('/etc/passwd',function(err, data){ if(err)throw err; console.log(data); });
Interfacing with node.js varreadFile=Q.denodeify(FS.readFile); var promise =readFile("/etc/passwd"); promise.then(function(data){ console.log(data) },function(err){ console.log('ERR', err); });
Why Promises are awesome • Cleaner method signatures • Easy composition • Easy to handle sequential and parallel flow • Always asynchronous • Uncomplicated error handling
Thanks for listening garren@redcometlabs.com Wanna learn more? Speak to me about Javascript training.