{"id":1458,"date":"2021-10-26T02:53:23","date_gmt":"2021-10-26T02:53:23","guid":{"rendered":"https:\/\/usemynotes.com\/?p=1458"},"modified":"2023-06-07T18:08:22","modified_gmt":"2023-06-07T18:08:22","slug":"promises-in-javascript","status":"publish","type":"post","link":"https:\/\/usemynotes.com\/promises-in-javascript\/","title":{"rendered":"How to Create a Promises in JavaScript?"},"content":{"rendered":"<p>Hi everyone, welcome back. In this module, I will be discussing <strong>Promises in JavaScript<\/strong>. If you want to know about the features included in the latest version of JavaScript, then you can read our previous module in which I have discussed it. So, without any further delay, let\u2019s get started to know Promises in JavaScript.<\/p>\n<p><img decoding=\"async\" class=\"alignnone wp-image-1459 size-full\" src=\"https:\/\/usemynotes.com\/wp-content\/uploads\/2021\/10\/promises-in-javascript.jpg\" alt=\"Promises in JavaScript\" width=\"1000\" height=\"700\" title=\"\" srcset=\"https:\/\/usemynotes.com\/wp-content\/uploads\/2021\/10\/promises-in-javascript.jpg 1000w, https:\/\/usemynotes.com\/wp-content\/uploads\/2021\/10\/promises-in-javascript-300x210.jpg 300w, https:\/\/usemynotes.com\/wp-content\/uploads\/2021\/10\/promises-in-javascript-768x538.jpg 768w, https:\/\/usemynotes.com\/wp-content\/uploads\/2021\/10\/promises-in-javascript-150x105.jpg 150w, https:\/\/usemynotes.com\/wp-content\/uploads\/2021\/10\/promises-in-javascript-696x487.jpg 696w, https:\/\/usemynotes.com\/wp-content\/uploads\/2021\/10\/promises-in-javascript-600x420.jpg 600w, https:\/\/usemynotes.com\/wp-content\/uploads\/2021\/10\/promises-in-javascript-100x70.jpg 100w\" sizes=\"(max-width: 1000px) 100vw, 1000px\" \/><\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 eztoc-toggle-hide-by-default' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/usemynotes.com\/promises-in-javascript\/#Promises_in_JavaScript\" >Promises in JavaScript<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/usemynotes.com\/promises-in-javascript\/#What_are_the_states_of_Promises_in_JavaScript\" >What are the states of Promises in JavaScript?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/usemynotes.com\/promises-in-javascript\/#How_to_create_a_promise_in_JavaScript\" >How to create a promise in JavaScript?<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/usemynotes.com\/promises-in-javascript\/#then_for_a_resolved_promise\" >then() for a resolved promise<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/usemynotes.com\/promises-in-javascript\/#catch_method_for_rejected_promise\" >catch() method for rejected promise<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/usemynotes.com\/promises-in-javascript\/#How_to_convert_promise_to_array_in_JavaScript\" >How to convert promise to array in JavaScript?<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"Promises_in_JavaScript\"><\/span>Promises in JavaScript<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>In JavaScript, promises are used for handling asynchronous operations. When dealing with several asynchronous activities, callbacks might create callback hell, which leads to unmanageable code, and then promises become easy to manage. Promises in JavaScript provide better handling of errors than events and callbacks. It was introduced in <a href=\"https:\/\/usemynotes.com\/latest-version-of-ecmascript\/\">ECMAScript 2015<\/a> or ES6.<\/p>\n<p>A JavaScript promise is like a real-world promise. A promise has 2 possible results: either it will be kept at the right moment or it will not. The same is true with JavaScript promises. When we define a promise in JavaScript, it is either resolved or rejected.<\/p>\n<p>A promise is defined as an object that can produce a single value in the future: either a resolved value or a reason for an unresolved promise. It has two properties: state &amp; result.<\/p>\n<p>Now, let\u2019s see what the states of JavaScript promises are.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"What_are_the_states_of_Promises_in_JavaScript\"><\/span>What are the states of Promises in JavaScript?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Promises in JavaScript have three states:<\/p>\n<ul>\n<li><strong>Pending<\/strong>: Promise is neither resolved nor rejected.<\/li>\n<li><strong>Fulfilled or Resolved<\/strong>: Promise is completed. The resultant value is a resolved value.<\/li>\n<li><strong>Rejected<\/strong>: Promise is not fulfilled. The resultant value is an error object.<\/li>\n<\/ul>\n<p>For example, when a user requests data from the server with a promise, it remains in a pending state till we are receiving our data. The promise will be resolved successfully if we acquire the requested information from the server. However, if we do not receive the information, then the Promise will be rejected.<\/p>\n<p>Let\u2019s now see how to create <strong>promises in JavaScript<\/strong>.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"How_to_create_a_promise_in_JavaScript\"><\/span>How to create a promise in JavaScript?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>In JavaScript, a promise object can be created by using the Promise constructor.<\/p>\n<p><strong>Syntax<\/strong><br \/>\nlet promise = new Promise(function(resolve, reject){<br \/>\n\/\/statements<br \/>\n});<\/p>\n<p>The promise constructor takes a callback <a href=\"https:\/\/usemynotes.com\/what-are-functions-in-javascript\/\">function<\/a> as an argument. The callback function takes 2 parameters: resolve for fulfilled promise &amp; reject for the failure of the promise.<\/p>\n<p>The callback function inside the new Promise object is called the <strong>executor<\/strong>. The executor is automatically executed when a new promise is produced. A promise consists of producing code &amp; consuming code.<\/p>\n<p>A &#8220;producing code&#8221; is a set of statements that performs some operation &amp; it takes time. It produces some results that will be used by the consuming code.<\/p>\n<p>A &#8220;consuming code&#8221; is a set of statements that waits for the result from the producing code. A promise is a JavaScript object, which links the &#8220;production code&#8221; along with the &#8220;consumer code.&#8221;<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">let promise = new Promise(function(resolve, reject) {\r\n\/\/ producing code\r\nconst a = &quot;hello&quot;;\r\nconst b = &quot;Hello&quot;\r\n  if(a === b) {\r\n    resolve(); \/\/ call on fulfilled promise.\r\n}\r\nelse {\r\n  reject(); \/\/ call on rejected promise.\r\n}\r\n});\r\n\r\n\/\/ consuming code, waiting for a promise to be resolved or fulfilled.\r\npromise.then(function () {\r\n  console.log(&#039;The promise is fulfilled.&#039;);\r\n}).catch(function () {\r\n  console.log(&#039;The promise is rejected.&#039;);\r\n});\r\n\r\n\/\/Output\r\n\/\/The promise is rejected.<\/pre>\n<h3><span class=\"ez-toc-section\" id=\"then_for_a_resolved_promise\"><\/span>then() for a resolved promise<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The then() method takes the callback function for the resolved promise as the first argument &amp; the callback function for the rejected promise as the second argument.<br \/>\nAfter the promise is resolved, we can decide what to do next.<br \/>\n<strong>Syntax<\/strong><\/p>\n<p>.then(function(result){<br \/>\n\/\/ statements to be executed on fulfilled promise<br \/>\n}, function(error){<br \/>\n\/\/ statements to be executed on rejected promise<br \/>\n});<\/p>\n<p>For example,<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">let promise = new Promise(function(resolve, reject) {\r\n  resolve(&#039;Resolved Promise&#039;);\r\n})\r\npromise.then(function(success) {\r\n  console.log(success);\r\n},function(error) {\r\n  console.log(error);\r\n});\r\n\/\/Output\r\n\/\/Resolved Promis<\/pre>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">let promise = new Promise(function(resolve, reject) {\r\n  reject(&#039;Rejected Promise&#039;);\r\n})\r\npromise.then(function(success) {\r\n  console.log(success);\r\n},function(error) {\r\n  console.log(error);\r\n});\r\n\/\/Output\r\n\/\/Rejected Promise<\/pre>\n<h3><span class=\"ez-toc-section\" id=\"catch_method_for_rejected_promise\"><\/span>catch() method for rejected promise<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>It is executed when some error occurs or a promise is rejected.<\/p>\n<p><strong>Syntax<\/strong><br \/>\n.catch(function(error){<br \/>\n\/\/ handling error for rejected promise<br \/>\n});<\/p>\n<p>For example,<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">let promise = new Promise(function(resolve, reject) {\r\n  reject(&#039;Promise Rejected&#039;)\r\n})\r\n\r\npromise.then(function(success) {\r\n  console.log(success);\r\n}).catch(function(error) {\r\n  console.log(error);\r\n});\r\n\/\/Output\r\n\/\/Promise Rejected<\/pre>\n<h2><span class=\"ez-toc-section\" id=\"How_to_convert_promise_to_array_in_JavaScript\"><\/span>How to convert promise to array in JavaScript?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>We can convert a list of promises into an <a href=\"https:\/\/usemynotes.com\/arrays-in-javascript\/\">array<\/a> by using the Promise.all() static methods in JavaScript. The Promise.all() Method takes an iterable of promises as an input, returning a single promise to an array of input promises. This returned promise will resolve when all input promises have been resolved or rejected if any of the input promises has been rejected.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">const p1 = Promise.resolve(10);\r\nconst p2 = 50;\r\nconst p3 = new Promise((resolve, reject) =&gt; {\r\n  setTimeout(resolve, 200, &#039;Hello&#039;);\r\n});\r\nPromise.all(&#x5B;p1, p2, p3]).then((value) =&gt; {\r\n  console.log(value);\r\n});\r\n\r\n\/\/Output\r\n\/\/Array &#x5B;10, 50, &quot;Hello&quot;]<\/pre>\n<p>I hope this module will be beneficial &amp; now you have got some basic knowledge of <strong>Promises in JavaScript<\/strong> &amp; how to create promises. As a beginner, it will take some time to understand properly how promises work, but by practising it, you will get to know about it. In the next module, I will be discussing async &amp; await in JavaScript. You can refer to our website for getting more informative modules like this.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hi everyone, welcome back. In this module, I will be discussing Promises in JavaScript. If you want to know about the features included in the latest version of JavaScript, then you can read our previous module in which I have discussed it. So, without any further delay, let\u2019s get started to know Promises in JavaScript. [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1459,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[14],"tags":[],"class_list":{"0":"post-1458","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-javascript"},"_links":{"self":[{"href":"https:\/\/usemynotes.com\/wp-json\/wp\/v2\/posts\/1458","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/usemynotes.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/usemynotes.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/usemynotes.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/usemynotes.com\/wp-json\/wp\/v2\/comments?post=1458"}],"version-history":[{"count":0,"href":"https:\/\/usemynotes.com\/wp-json\/wp\/v2\/posts\/1458\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/usemynotes.com\/wp-json\/wp\/v2\/media\/1459"}],"wp:attachment":[{"href":"https:\/\/usemynotes.com\/wp-json\/wp\/v2\/media?parent=1458"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/usemynotes.com\/wp-json\/wp\/v2\/categories?post=1458"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/usemynotes.com\/wp-json\/wp\/v2\/tags?post=1458"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}