{"id":59895,"date":"2018-05-03T16:01:10","date_gmt":"2018-05-03T10:31:10","guid":{"rendered":"https:\/\/www.vskills.in\/certification\/tutorial\/?p=59895"},"modified":"2024-04-12T14:20:50","modified_gmt":"2024-04-12T08:50:50","slug":"angular-promises","status":"publish","type":"page","link":"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/","title":{"rendered":"Angular Promises"},"content":{"rendered":"<h1>Angular Promises<\/h1>\n<p>Promises are a pattern that helps with one particular kind of asynchronous programming: a function (or method) that returns a single result asynchronously. One popular way of receiving such a result is via a callback (\u201ccallbacks as continuations\u201d):<\/p>\n<p>asyncFunction(arg1, arg2,<\/p>\n<p>result =&gt; {<\/p>\n<p>console.log(result);<\/p>\n<p>});<\/p>\n<p>Promises are not actually complicated, they&#8217;re objects that contain a reference to functions to call when something fails or succeeds.<\/p>\n<p>Under the hood, AngularJS actually wires up a promise for an HTTP request in a way a bit like this:<\/p>\n<p>var request = new XMLHttpRequest();<br \/>\nrequest.addEventListener(&#8220;load&#8221;, function() {<br \/>\n\/\/ complete the promise<br \/>\n}, false);<br \/>\nrequest.addEventListener(&#8220;error&#8221;, function() {<br \/>\n\/\/ fail the promise<br \/>\n}, false);<br \/>\nrequest.open(&#8220;GET&#8221;, &#8220;\/api\/my\/name&#8221;, true);<br \/>\nrequest.send();<\/p>\n<p>this is pseudo-code, but the idea is that its the browser that calls us back, via the event listeners, then AngularJS can just call the appropriate method on the promise.<\/p>\n<p>Now in AngularJS, the promises are created with the $q service (we&#8217;ll see exactly how to do this shortly), but why $q?<\/p>\n<p>The reason the service is named $q is that AngularJS&#8217; promise implementation is based on Kris Kowal&#8217;s promise mechanism, which is called &#8216;Q&#8217;. You can see the library at github.com\/kristkowal\/q.<\/p>\n<p>This was a deliberate decision, as the Q library is widely used and well understood by the community. We&#8217;re going to see a little bit later what the future of promises is in AngularJS and actually in ECMAScript 6.<br \/>\nA Real World Example<\/p>\n<p>In this example, we&#8217;ll create a service that gets the user&#8217;s name, just like in our examples. However, to make it interesting, we&#8217;ll set our service up so that the first time we get the name from the server, and then afterwards we&#8217;ll return a cached copy.<\/p>\n<p>This means we&#8217;ll have to build our code to deal with the asynchronous case (the first one) and the more trivial synchronous case (getting the name from the cache).<\/p>\n<p>Let&#8217;s look at a pure asynchronous implementation.<\/p>\n<p>app.factory(&#8216;NameService&#8217;, function($http, $q) {<\/p>\n<p>\/\/ Create a class that represents our name service.<br \/>\nfunction NameService() {<\/p>\n<p>var self = this;<\/p>\n<p>\/\/ getName returns a promise which when<br \/>\n\/\/ fulfilled returns the name.<br \/>\nself.getName = function() {<br \/>\nreturn $http.get(&#8216;\/api\/my\/name&#8217;);<br \/>\n};<br \/>\n}<\/p>\n<p>return new NameService();<br \/>\n});<\/p>\n<p>Now let&#8217;s update our service so that we hit the server only if we haven&#8217;t already cached the name. I&#8217;ll build the service blow by blow, then we can see a fiddle of it working.<\/p>\n<p>app.factory(&#8216;NameService&#8217;, function($http, $q) {<\/p>\n<p>\/\/ Create a class that represents our name service.<br \/>\nfunction NameService() {<\/p>\n<p>var self = this;<\/p>\n<p>\/\/ Initially the name is unknown&#8230;.<br \/>\nself.name = null;<\/p>\n<p>so first we create a service which is in the form of a class. It has a name field which is initially null.<\/p>\n<p>self.getName = function() {<br \/>\n\/\/ Create a deferred operation.<br \/>\nvar deferred = $q.defer();<\/p>\n<p>Now in the getName function we start by creating a deferred object, using the $q service. This object contains the promise we&#8217;ll return, and has some helper functions to let us build the promise.<\/p>\n<p>We create a deferred object because whether we use ajax or not, we want the consumer to use the promise &#8211; even if we can return straightaway in some circumstances (when we have the name) we can&#8217;t in all &#8211; so the caller must always expect a promise.<\/p>\n<p>if(self.name !== null) {<br \/>\ndeferred.resolve(self.name + &#8221; (from Cache!)&#8221;);<br \/>\n}<\/p>\n<p>If we already have the name, we can just resolve the deferred object immediately &#8211; this is the easy case. I&#8217;ve added &#8216;from cache&#8217; to the name so we can see when it comes from the cache compared to the server.<\/p>\n<p>Finally, we can handle the case if we don&#8217;t already have the name:<\/p>\n<p>else {<br \/>\n\/\/ Get the name from the server.<br \/>\n$http.get(&#8216;\/api\/my\/name\/&#8217;)<br \/>\n.success(function(name) {<br \/>\nself.name = name;<br \/>\ndeferred.resolve(name + &#8221; (from Server!)&#8221;);<br \/>\n})<br \/>\n.error(function(response) {<br \/>\ndeferred.reject(response);<br \/>\n});<br \/>\n}<\/p>\n<p>So if we get success from the server, we can resolve the promise. Otherwise, we reject it, which means failure.<\/p>\n<p class=\"VSKILLbodytext\"><strong>IT Professionals, Web Developers, web programmers, IT students can Apply for the certification course and get ahead.<\/strong><\/p>\n<p><a href=\"https:\/\/www.vskills.in\/certification\/web-development\/angular-4-certification\" rel=\"attachment wp-att-61497\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-61497\" src=\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2018\/04\/Angular-4.png\" sizes=\"auto, (max-width: 1050px) 100vw, 1050px\" srcset=\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2018\/04\/Angular-4.png 1050w, https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2018\/04\/Angular-4-300x48.png 300w, https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2018\/04\/Angular-4-768x124.png 768w, https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2018\/04\/Angular-4-1024x165.png 1024w, https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2018\/04\/Angular-4-712x115.png 712w\" alt=\"\" width=\"1050\" height=\"169\" \/><\/a><\/p>\n<ul>\n<li class=\"VSKILLbodytext\"><a href=\"https:\/\/www.vskills.in\/practice\/skills\/Web-Development\/Angular-4\" target=\"_blank\" rel=\"noopener\">Practice Test for Angular4 <\/a><\/li>\n<li class=\"VSKILLbodytext\"><a href=\"https:\/\/www.vskills.in\/certification\/web-development\/angular-4-certification\" target=\"_blank\" rel=\"noopener\">Govt Certification in Angular 4<\/a><\/li>\n<li><a href=\"https:\/\/www.vskills.in\/certification\/blog\/\">Blog posts on Angular 4 and Web Development<\/a><\/li>\n<\/ul>\n<p><a href=\"https:\/\/www.vskills.in\/certification\/tutorial\/web-development\/angular-4\/\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-55483 size-full\" src=\"http:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/05\/Back-Arrow.jpg\" alt=\"Angular 4 Tutorial Index\" width=\"47\" height=\"52\" \/>Back to Angular 4 Tutorial Main Page <\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Angular Promises Promises are a pattern that helps with one particular kind of asynchronous programming: a function (or method) that returns a single result asynchronously. One popular way of receiving such a result is via a callback (\u201ccallbacks as continuations\u201d): asyncFunction(arg1, arg2, result =&gt; { console.log(result); }); Promises are not actually complicated, they&#8217;re objects that&#8230;<\/p>\n","protected":false},"author":10,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"categories":[7230,7231,5743],"tags":[7221,7227,7235,7236,7226,7234,7414,7413,7232,7223,7233],"class_list":["post-59895","page","type-page","status-publish","hentry","category-angular-2","category-angular-4","category-web-development","tag-angular","tag-angular-4","tag-angular-4-tutorial","tag-angular-cli","tag-angular-js","tag-angular-js-tutorial","tag-angular-promise","tag-angular-promises","tag-angular-tutorial","tag-angularjs","tag-angularjs-tutorial"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Angular Promises - Tutorial<\/title>\n<meta name=\"description\" content=\"Angular Promises are a pattern that helps with one particular kind of asynchronous programming. Read here.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Angular Promises - Tutorial\" \/>\n<meta property=\"og:description\" content=\"Angular Promises are a pattern that helps with one particular kind of asynchronous programming. Read here.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/\" \/>\n<meta property=\"og:site_name\" content=\"Tutorial\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/vskills.in\/\" \/>\n<meta property=\"article:modified_time\" content=\"2024-04-12T08:50:50+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2018\/04\/Angular-4.png\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/\",\"name\":\"Angular Promises - Tutorial\",\"isPartOf\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2018\/04\/Angular-4.png\",\"datePublished\":\"2018-05-03T10:31:10+00:00\",\"dateModified\":\"2024-04-12T08:50:50+00:00\",\"description\":\"Angular Promises are a pattern that helps with one particular kind of asynchronous programming. Read here.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/#primaryimage\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2018\/04\/Angular-4.png\",\"contentUrl\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2018\/04\/Angular-4.png\",\"width\":1050,\"height\":169},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Angular Promises\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"name\":\"Tutorial\",\"description\":\"Vskills - A initiative in elearning and certification\",\"publisher\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\",\"name\":\"Vskills\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"contentUrl\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"width\":73,\"height\":55,\"caption\":\"Vskills\"},\"image\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/vskills.in\/\",\"https:\/\/x.com\/vskills_in\",\"https:\/\/www.linkedin.com\/company-beta\/1371554\/\",\"https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Angular Promises - Tutorial","description":"Angular Promises are a pattern that helps with one particular kind of asynchronous programming. Read here.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/","og_locale":"en_US","og_type":"article","og_title":"Angular Promises - Tutorial","og_description":"Angular Promises are a pattern that helps with one particular kind of asynchronous programming. Read here.","og_url":"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/","og_site_name":"Tutorial","article_publisher":"https:\/\/www.facebook.com\/vskills.in\/","article_modified_time":"2024-04-12T08:50:50+00:00","og_image":[{"url":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2018\/04\/Angular-4.png","type":"","width":"","height":""}],"twitter_misc":{"Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/","name":"Angular Promises - Tutorial","isPartOf":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/#primaryimage"},"image":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/#primaryimage"},"thumbnailUrl":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2018\/04\/Angular-4.png","datePublished":"2018-05-03T10:31:10+00:00","dateModified":"2024-04-12T08:50:50+00:00","description":"Angular Promises are a pattern that helps with one particular kind of asynchronous programming. Read here.","breadcrumb":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/#primaryimage","url":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2018\/04\/Angular-4.png","contentUrl":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2018\/04\/Angular-4.png","width":1050,"height":169},{"@type":"BreadcrumbList","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/angular-promises\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.vskills.in\/certification\/tutorial\/"},{"@type":"ListItem","position":2,"name":"Angular Promises"}]},{"@type":"WebSite","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","name":"Tutorial","description":"Vskills - A initiative in elearning and certification","publisher":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization","name":"Vskills","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","contentUrl":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","width":73,"height":55,"caption":"Vskills"},"image":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/vskills.in\/","https:\/\/x.com\/vskills_in","https:\/\/www.linkedin.com\/company-beta\/1371554\/","https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw"]}]}},"_links":{"self":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/59895","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/users\/10"}],"replies":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/comments?post=59895"}],"version-history":[{"count":7,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/59895\/revisions"}],"predecessor-version":[{"id":64258,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/59895\/revisions\/64258"}],"wp:attachment":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/media?parent=59895"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/categories?post=59895"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/tags?post=59895"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}