{"id":63,"date":"2016-02-28T04:38:08","date_gmt":"2016-02-28T04:38:08","guid":{"rendered":"http:\/\/165.225.137.195\/blog\/?p=63"},"modified":"2016-02-28T04:38:08","modified_gmt":"2016-02-28T04:38:08","slug":"promisesdeferred-objects-asynchronous-computations","status":"publish","type":"post","link":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/2016\/02\/28\/promisesdeferred-objects-asynchronous-computations\/","title":{"rendered":"Promises\/deferred objects &#8211; asynchronous computations"},"content":{"rendered":"<p><strong><em>Definition: (ECMA-2015)<\/em><\/strong><br \/>\nA Promise is an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation.<br \/>\nA Promise represents an operation that hasn&#8217;t completed yet, but is expected in the future, while it\u2019s in execution. Promises are very useful for remote calls to overcome network latency, once network responded promise will resolve or reject based on returned data.<br \/>\n<strong>Promise Abstract Operations:<\/strong><br \/>\n[table class=&#8221;table table-striped&#8221;]<br \/>\nField Name,Value type,Meaning<br \/>\n<em>[[Promise]]<\/em>, An object, An object that is usable as a promise.<br \/>\n<em>[[Resolve]]<\/em>, A function object, The function that is used to resolve the given promise object.<br \/>\n<em>[[Reject]]<\/em>, A function object, the function that is used to reject the given promise object.<br \/>\n[\/table]<br \/>\nWe are using angular 1.x $q service to illustrate promises. $q is a similar implementation of promises concept by Kris Kowal&#8217;s Q.js. we can generate a new instance of promise by calling $q.defer(), which is equals new Promise() in ES 6. Deferred object contains promise property which is responsible for callback function executions such as onFulfilled, onRejected and progressBack.<br \/>\nFlex frameworks Action Script 3.0 also have a similar implementation like Q.js as AsyncToken,AsyncResponder. The syntax looks like below<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\n\/\/Flex AsyncToken usage\nvar token:AsyncToken = service.send();\ntoken.addResponder(new mx.rpc.Responder(result, fault));\n<\/pre>\n<p><strong>The $q object:<\/strong><br \/>\n[table class=&#8221;table table-striped&#8221;]<br \/>\nMethod Name,Meaning<br \/>\n<em>$q. defer()<\/em>,new instance of promise\u00a0will returns a deferred object<br \/>\n<em>$q.all(ArrayOfPromises)<\/em>,Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.<br \/>\n[\/table]<br \/>\n<strong>The Deferred object:<\/strong><br \/>\n<em>$q.defer()<\/em> will returns a deferred object, which have below methods:<br \/>\n[table class=&#8221;table table-striped&#8221;]<br \/>\nMethod Name,Meaning<br \/>\n<em>deferred.resolve(value)<\/em>,resolves the derived promise with the value.<br \/>\n<em>deferred.reject(reason)<\/em>,rejects the derived promise with the reason.<br \/>\n<em>deferred.notify(value)<\/em>,provides updates on the status of the promise&#8217;s execution. This may be called multiple times before the promise is either resolved or rejected.<br \/>\n<em>deferred.promise{}<\/em>, An object that is usable as a promise<br \/>\n[\/table]<br \/>\n<strong>The Promise object:<\/strong><br \/>\n[table class=&#8221;table table-striped&#8221;]<br \/>\nMethod Name,Meaning<br \/>\n&#8220;<em>then:function(onFulfilled, onRejected, progressBack)<\/em>&#8220;, &#8220;it will hook result,fault and progress methods to a promise. then calls one of the callback methods asynchronously as soon as the result is available.&#8221;<br \/>\n<em>catch(errorCallback)<\/em>, &#8220;shorthand for promise.then(null, errorCallback).one more way to provide fault method.&#8221;<br \/>\n[\/table]<br \/>\nBelow example will illustrate promises usage,<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\n\/\/$q for promises\n\/\/create module\nvar myApp = angular.module(&quot;promisesApp&quot;,&#x5B;]);\n\/\/get $q as global Q for better and simple analysis\nangular.injector(&#x5B;'ng', 'promisesApp']).invoke(function ($q) {window.Q = $q;});\n\/\/promisesApp.controller(&quot;promisCtrl&quot;,&#x5B;&quot;$q&quot;,function(Q){\nfunction result(response){\n console.log(&quot;Resolved and Response is:&quot;+response);\n }\nfunction fault(reason){\n console.log(&quot;Rejected and Error info: &quot;+reason);\n }\nfunction notify(update){\n console.log(&quot;Notification: &quot;+update);\n }\nfunction asyncExecution(resultObj,isResolvable,atTime){\n var defered = Q.defer();\n var promise = defered.promise;\n \/\/Simulating network latency\n setTimeout(function(isResolvable){\n if(isResolvable){\n defered.notify('resolving now...');\n defered.resolve(resultObj);\n defered.notify('resolved');\/\/notify Never prints, once promise resolved or rejects\n }\n else{\n defered.notify('rejecting now...');\n defered.reject(&quot;Got an Error&quot;);\n defered.notify('rejected');\/\/notify Never prints, once promise resolved or rejects\n }\n },atTime,isResolvable);\n return promise;\n}\nvar p1 = asyncExecution('p1',true,2000);\np1.then(result,fault,notify);\nvar p2 = asyncExecution('p2',false,3000);\np2.then(result,fault,notify);\nvar p3 = asyncExecution('p3',true,4000);\np3.then(result,fault,notify);\n<\/pre>\n<p>Output as following:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nNotification: resolving now...\nResolved and Response is:p1\nNotification: rejecting now...\nRejected and Error info: Got an Error\nNotification: resolving now...\nResolved and Response is:p3\n<\/pre>\n<p><strong>Promises Chaining:<\/strong><br \/>\nChaining is useful when we need to make synchronous calls to server. always\u00a0promises will look for <em>failure handler,<\/em> if not present in current then-able it will look for next available then-able. chaining will continue only if a success handler on <em>returning a promise object<\/em>. \u00a0below example will explain about chaining of multiple promises.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\n\/\/Chaining\nvar p1 = asyncExecution('p1',true,2000);\nvar p2 = asyncExecution('p2',true,3000);\nvar p3 = asyncExecution('p3',true,4000);\n\/\/promises will look for failure handler, if not present\n\/\/in current then-able it will look for next available then-able\np1.then(function(a){result(a);return p2})\n\/\/return Promise to continue chaining\n.then(function(a){result(a);return p3})\n.then(result);\n<\/pre>\n<p>Output as following:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nResolved and Response is:p1\nResolved and Response is:p2\nResolved and Response is:p3\n<\/pre>\n<p><strong>Combine Multiple promises as one promise:<\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\n\/\/let combin and know all promises are done or not\nvar p1 = asyncExecution('p1',true,2000);\nvar p2 = asyncExecution('p2',true,3000);\nvar p3 = asyncExecution('p3',true,4000);\nQ.all(&#x5B;p1,p2,p3])\n.then(function(){console.log('All Async tasks done')},\n     function(){console.log('Failed:Soming worng!!')})\n.finally(function(){\n     console.log('Finally: I will execute any way')});\n<\/pre>\n<p>Output as following:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nAll Async tasks done\nFinally: I will execute any way\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Definition: (ECMA-2015) A Promise is an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation. A Promise represents an operation that hasn&#8217;t completed yet, but is&hellip; <a href=\"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/2016\/02\/28\/promisesdeferred-objects-asynchronous-computations\/\">More<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2,3,8,12,13,14,15,17],"tags":[],"class_list":["post-63","post","type-post","status-publish","format-standard","hentry","category-angular","category-angular-1-4","category-async","category-ecma-2015","category-ecma5","category-ecma6","category-javascript","category-q-js"],"_links":{"self":[{"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/63","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=63"}],"version-history":[{"count":0,"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/63\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=63"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=63"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bhoomabrsr.com\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=63"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}