{"id":29623,"date":"2019-04-08T23:29:09","date_gmt":"2019-04-08T15:29:09","guid":{"rendered":"https:\/\/www.hongkiat.com\/blog\/?p=29623"},"modified":"2022-10-09T21:34:26","modified_gmt":"2022-10-09T13:34:26","slug":"javascript-promise-object","status":"publish","type":"post","link":"https:\/\/www.hongkiat.com\/blog\/javascript-promise-object\/","title":{"rendered":"Getting Started with JavaScript Promises"},"content":{"rendered":"<p><strong>Asynchronous code<\/strong> is useful for performing tasks that are <strong>time-consuming<\/strong> but, of course, it\u2019s <strong>not devoid of cons<\/strong>. Async code uses <strong>callback functions<\/strong> to process its results, however callback functions <strong>cannot return values<\/strong> that typical JavaScript functions can.<\/p>\n<p class=\"recommended_top\">\n\t\t\t\t\t<strong>Read Also:<\/strong>\u00a0\n\t\t\t\t\t<a target=\"_blank\" href=\"https:\/\/www.hongkiat.com\/blog\/synchronous-asynchronous-javascript\/\">Mastering Synchronous & Asynchronous JavaScript \u2013 Part 1<\/a>\n\t\t\t\t<\/p>\n<p>Thus, they not only take away our ability to control the <strong>execution of the function<\/strong> but also make <strong>error handling<\/strong> a bit of a hassle. This is where the <strong><a href=\"https:\/\/developer.mozilla.org\/en\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Promise\" target=\"_blank\" rel=\"noopener\"><code>Promise<\/code><\/a> object<\/strong> comes in, as it aims to fill in some of the <strong>potholes in asynchronous coding<\/strong>.<\/p>\n<p><code>Promise<\/code> is technically a <strong>standard internal object<\/strong> in JavaScript, meaning it comes <strong>built-in to JavaScript<\/strong>. It is used to represent the <strong>eventual result of an asynchronous code block<\/strong> (or the reason why the code failed) and has methods to control the <strong>execution of the asynchronous code<\/strong>.<\/p>\n<h2>Syntax<\/h2>\n<p>We can create <strong>an instance of the <code>Promise<\/code> object<\/strong> using the <code>new<\/code> keyword:<\/p>\n<pre>\r\nnew Promise(function(resolve, reject) {} );\r\n<\/pre>\n<p>The function <strong>passed as a parameter<\/strong> to the <code>Promise()<\/code> constructor is known as the <strong>executor<\/strong>. It holds the asynchronous code and <strong>has two parameters of the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Function\" target=\"_blank\" rel=\"noopener\"><code>Function<\/code><\/a> type<\/strong>, referred to as <strong><code>resolve<\/code><\/strong> and <strong><code>reject<\/code><\/strong> functions (more on these shortly).<\/p>\n<h2>States of the <code>Promise<\/code> object<\/h2>\n<p>The <strong>initial state<\/strong> of a <code>Promise<\/code> object is called <strong><em>pending<\/em><\/strong>. In this state, the result of the asynchronous computation <strong>does not exist<\/strong>.<\/p>\n<p>The initial pending state changes to <strong><em>fulfilled<\/em><\/strong> state when the computation is <strong>successful<\/strong>. The <strong>result of the computation<\/strong> is available in this state.<\/p>\n<p>In case the asynchronous computation <strong>fails<\/strong>, the <code>Promise<\/code> object moves to the <strong><em>rejected<\/em><\/strong> state from its initial <em>pending<\/em> state. In this state, the <strong>reason of the computation failure<\/strong> (i.e. error message)  is made available.<\/p>\n<p>To go from <em>pending<\/em> to <em>fulfilled<\/em> state, <strong><code>resolve()<\/code> is called<\/strong>. To go from <em>pending<\/em> to <em>rejected<\/em> state, <strong><code>reject()<\/code> is called<\/strong>.<\/p>\n<figure><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/assets.hongkiat.com\/uploads\/javascript-promise-object\/promise-states.jpg\" alt=\"Three states of Promises\" width=\"665\" height=\"315\"><\/figure>\n<h2>The <code>then<\/code> and <code>catch<\/code> methods<\/h2>\n<p>When the state <strong>changes from <em>pending<\/em> to <em>fulfilled<\/em><\/strong>, the event handler of the <code>Promise<\/code> object\u2019s <strong><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Promise\/then\" target=\"_blank\" rel=\"noopener\"><code>then<\/code><\/a> method<\/strong> is executed. And, when the state <strong>changes from <em>pending<\/em> to <em>rejected<\/em><\/strong>, the event handler of the <code>Promise<\/code> object\u2019s <strong><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Promise\/catch\" target=\"_blank\" rel=\"noopener\"><code>catch<\/code><\/a> method<\/strong> is executed.<\/p>\n<h2>Example 1<\/h2>\n<h3>\u201cNon-Promisified\u201d code<\/h3>\n<p>Assume there\u2019s a <code>hello.txt<\/code> file containing the \u201cHello\u201d word. Here\u2019s how we can write an AJAX request to <strong>fetch that file<\/strong> and <strong>show its content<\/strong>, without using the <code>Promise<\/code> object:<\/p>\n<pre>\r\nfunction getTxt() {\r\n    let xhr = new XMLHttpRequest();\r\n    xhr.open('GET', 'hello.txt');\r\n    xhr.overrideMimeType('text\/plain');\r\n    xhr.send();\r\n    xhr.onload = function() {\r\n        try {\r\n            switch (this.status) {\r\n                case 200:\r\n                    document.write(this.response);\r\n                    break;\r\n                case 404:\r\n                    throw 'File Not Found';\r\n                default:\r\n                    throw 'Failed to fetch the file';\r\n            }\r\n        } catch (err) {\r\n            console.log(err)\r\n        }\r\n    };\r\n}\r\n\r\ngetTxt();\r\n<\/pre>\n<p>If the content of the file has been <strong>successfully fetched<\/strong>, i.e. <strong>the response status code is 200<\/strong>, the response text is <strong>written into the document<\/strong>. If the file is <strong>not found (status 404)<\/strong>, a <a href=\"https:\/\/www.hongkiat.com\/blog\/common-http-errors\/\">\u201cFile Not Found\u201d error message<\/a> is thrown. Otherwise, a <strong>general error message<\/strong> indicating the failure of fetching the file is thrown.<\/p>\n<h3>\u201cPromisified\u201d code<\/h3>\n<p>Now, let\u2019s <strong>Promisify the above code<\/strong>:<\/p>\n<pre>\r\nfunction getTxt() {\r\n    return new Promise(function(resolve, reject) {\r\n        let xhr = new XMLHttpRequest();\r\n        xhr.open('GET', 'hello.txt');\r\n        xhr.overrideMimeType('text\/plain');\r\n        xhr.send();\r\n        xhr.onload = function() {\r\n            switch (this.status) {\r\n                case 200:\r\n                    resolve(this.response);\r\n                case 404:\r\n                    reject('File Not Found');\r\n                default:\r\n                    reject('Failed to fetch the file');\r\n            }\r\n        };\r\n    });\r\n}\r\n\r\ngetTxt().then(\r\n    function(txt) {\r\n        document.write(txt);\r\n    }).catch(\r\n    function(err) {\r\n        console.log(err);\r\n    });\r\n<\/pre>\n<p>The <code>getTxt()<\/code> function is now coded to <strong>return a new instance of the <code>Promise<\/code> object<\/strong>, and its executor function holds the asynchronous code from before.<\/p>\n<p>When the <strong>response status code is 200<\/strong>, the <strong><code>Promise<\/code> is <em>fulfilled<\/em><\/strong> by <strong>calling <code>resolve()<\/code><\/strong> (the response is passed as the parameter of <code>resolve()<\/code>). When the status code is 404 or some other, the <strong><code>Promise<\/code> is <em>rejected<\/em><\/strong> <strong>using <code>reject()<\/code><\/strong> (with the appropriate error message as the parameter of <code>reject()<\/code>).<\/p>\n<p>The <strong>event handlers for the <code>then()<\/code> and <code>catch()<\/code> methods<\/strong> of the <code>Promise<\/code> object are <strong>added at the end<\/strong>.<\/p>\n<p>When the <strong><code>Promise<\/code> is <em>fulfilled<\/em><\/strong>, the handler of the <code>then()<\/code> method is run. Its argument is <strong>the parameter passed from <code>resolve()<\/code><\/strong>. Inside the event handler, the response text (received as the argument) is <strong>written into the document<\/strong>.<\/p>\n<p>When the <strong><code>Promise<\/code> is <em>rejected<\/em><\/strong>, the event handler of the <code>catch()<\/code> method is run, <strong>logging the error<\/strong>.<\/p>\n<p>The <strong>main advantage<\/strong> of the above Promisified version of the code is the <strong>error handling<\/strong>. Instead of throwing Uncaught Exceptions around\n  \u2014 like in the Non-Promisified version \u2014 the <strong>appropriate failure messages<\/strong> are returned and logged.<\/p>\n<p>But, it\u2019s not just the <strong>returning<\/strong> of the <strong>failure messages<\/strong> but also of the <strong>result of the asynchronous computation<\/strong> that can be truly advantageous for us. To see that, we\u2019ll need to expand our example.<\/p>\n<h2>Example 2<\/h2>\n<h3>\u201cNon-Promisified\u201d code<\/h3>\n<p>Instead of just displaying the text from <code>hello.txt<\/code>, I want to <strong>combine it with the \u201cWorld\u201d word<\/strong> and display it on the screen <strong>after a time-out of 2 seconds<\/strong>. Here\u2019s the code I use:<\/p>\n<pre>\r\nfunction getTxt() {\r\n    let xhr = new XMLHttpRequest();\r\n    xhr.open('GET', 'hello.txt');\r\n    xhr.overrideMimeType('text\/plain');\r\n    xhr.send();\r\n    xhr.onload = function() {\r\n        try {\r\n            switch (this.status) {\r\n                case 200:\r\n                    document.write(concatTxt(this.response));\r\n                    break;\r\n                case 404:\r\n                    throw 'File Not Found';\r\n                default:\r\n                    throw 'Failed to fetch the file';\r\n            }\r\n        } catch (err) {\r\n            console.log(err)\r\n        }\r\n    };\r\n}\r\n\r\nfunction concatTxt(res) {\r\n    setTimeout(function() {\r\n        return (res + 'World')\r\n    }, 2000);\r\n}\r\n\r\ngetTxt();\r\n<\/pre>\n<p>On the status code 200,  the <code>concatTxt()<\/code> function is called to <strong>concatenate the response text with the \u201cWorld\u201d word<\/strong> before writing it into document.<\/p>\n<p>But, this code <strong>won\u2019t work as desired<\/strong>. The <code>setTimeout()<\/code> callback function <strong>cannot return the concatenated string<\/strong>. What will be printed out to the document is <strong><code>undefined<\/code><\/strong> because that\u2019s <strong>what <code>concatTxt()<\/code> returns<\/strong>.<\/p>\n<h3>\u201cPromisified\u201d code<\/h3>\n<p>So, to make the code work, let\u2019s <strong>Promisify the above code<\/strong>, including <code>concatTxt()<\/code>:<\/p>\n<pre>\r\nfunction getTxt() {\r\n    return new Promise(function(resolve, reject) {\r\n        let xhr = new XMLHttpRequest();\r\n        xhr.open('GET', 'hello.txt');\r\n        xhr.overrideMimeType('text\/plain');\r\n        xhr.send();\r\n        xhr.onload = function() {\r\n            switch (this.status) {\r\n                case 200:\r\n                    resolve(this.response);\r\n                case 404:\r\n                    reject('File Not Found');\r\n                default:\r\n                    reject('Failed to fetch the file');\r\n            }\r\n        };\r\n    });\r\n}\r\n\r\nfunction concatTxt(txt) {\r\n    return new Promise(function(resolve, reject) {\r\n        setTimeout(function() {\r\n            resolve(txt + ' World');\r\n        }, 2000);\r\n    });\r\n}\r\n\r\ngetTxt().then(\r\n    (txt) = &gt; {\r\n        return concatTxt(txt);\r\n    }).then(\r\n    (txt) = &gt; {\r\n        document.write(txt);\r\n    }).catch(\r\n    (err) = &gt; {\r\n        console.log(err);\r\n    });\r\n<\/pre>\n<p>Just like <code>getTxt()<\/code>, the <code>concatTxt()<\/code> function also <strong>returns a new <code>Promise<\/code> object<\/strong> instead of the concatenated text. The <code>Promise<\/code> returned by <code>concatTxt()<\/code> is <strong>resolved inside callback function of <code>setTimeout()<\/code><\/strong>.<\/p>\n<p>Near the end of the above code, the event handler of the first <code>then()<\/code> method runs when the <strong><code>Promise<\/code> of <code>getTxt()<\/code> is <em>fulfilled<\/em><\/strong>, i.e. when the file is <strong>fetched successfully<\/strong>. Inside that handler, <strong><code>concatTxt()<\/code> is called<\/strong> and the <strong><code>Promise<\/code> returned by <code>concatTxt()<\/code> is returned<\/strong>.<\/p>\n<p>The event handler of the second <code>then()<\/code> method runs when the <strong><code>Promise<\/code> returned by <code>concatTxt()<\/code> is <em>fulfilled<\/em><\/strong>, i.e. the <strong>two seconds time-out is over<\/strong> and <strong><code>resolve()<\/code> is called<\/strong> with the concatenated string as its parameter.<\/p>\n<p>Finally, <code>catch()<\/code> <strong>catches all the exceptions and failure messages<\/strong> from both Promises.<\/p>\n<p>In this Promisified version, the \u201cHello World\u201d string will be <strong>successfully printed out<\/strong> to the document.<\/p>\n<p class=\"recommended_top\">\n\t\t\t\t\t<strong>Read Also:<\/strong>\u00a0\n\t\t\t\t\t<a target=\"_blank\" href=\"https:\/\/www.hongkiat.com\/blog\/dom-manipulation-javascript-methods\/\">Master DOM Manipulation with 15 Essential JavaScript Methods<\/a>\n\t\t\t\t<\/p>","protected":false},"excerpt":{"rendered":"<p>Asynchronous code is useful for performing tasks that are time-consuming but, of course, it\u2019s not devoid of cons. Async code uses callback functions to process its results, however callback functions cannot return values that typical JavaScript functions can. Thus, they not only take away our ability to control the execution of the function but also&hellip;<\/p>\n","protected":false},"author":145,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[3392],"tags":[4117,511],"topic":[4520],"class_list":["entry-content","is-maxi"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v22.8 (Yoast SEO v27.6) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Getting Started with JavaScript Promises - Hongkiat<\/title>\n<meta name=\"description\" content=\"Asynchronous code is useful for performing tasks that are time-consuming but, of course, it&#039;s not devoid of cons. Async code uses callback functions to\" \/>\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.hongkiat.com\/blog\/javascript-promise-object\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Getting Started with JavaScript Promises\" \/>\n<meta property=\"og:description\" content=\"Asynchronous code is useful for performing tasks that are time-consuming but, of course, it&#039;s not devoid of cons. Async code uses callback functions to\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.hongkiat.com\/blog\/javascript-promise-object\/\" \/>\n<meta property=\"og:site_name\" content=\"Hongkiat\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/hongkiatcom\" \/>\n<meta property=\"article:published_time\" content=\"2019-04-08T15:29:09+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-10-09T13:34:26+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/assets.hongkiat.com\/uploads\/javascript-promise-object\/promise-states.jpg\" \/>\n<meta name=\"author\" content=\"Preethi Ranjit\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@hongkiat\" \/>\n<meta name=\"twitter:site\" content=\"@hongkiat\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Preethi Ranjit\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/javascript-promise-object\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/javascript-promise-object\\\/\"},\"author\":{\"name\":\"Preethi Ranjit\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#\\\/schema\\\/person\\\/e981676afae36d1ff5feb75094950ab3\"},\"headline\":\"Getting Started with JavaScript Promises\",\"datePublished\":\"2019-04-08T15:29:09+00:00\",\"dateModified\":\"2022-10-09T13:34:26+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/javascript-promise-object\\\/\"},\"wordCount\":847,\"commentCount\":2,\"publisher\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/javascript-promise-object\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/assets.hongkiat.com\\\/uploads\\\/javascript-promise-object\\\/promise-states.jpg\",\"keywords\":[\"Javascripts\",\"Web Developers\"],\"articleSection\":[\"Coding\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/javascript-promise-object\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/javascript-promise-object\\\/\",\"url\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/javascript-promise-object\\\/\",\"name\":\"Getting Started with JavaScript Promises - Hongkiat\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/javascript-promise-object\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/javascript-promise-object\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/assets.hongkiat.com\\\/uploads\\\/javascript-promise-object\\\/promise-states.jpg\",\"datePublished\":\"2019-04-08T15:29:09+00:00\",\"dateModified\":\"2022-10-09T13:34:26+00:00\",\"description\":\"Asynchronous code is useful for performing tasks that are time-consuming but, of course, it's not devoid of cons. Async code uses callback functions to\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/javascript-promise-object\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/javascript-promise-object\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/javascript-promise-object\\\/#primaryimage\",\"url\":\"https:\\\/\\\/assets.hongkiat.com\\\/uploads\\\/javascript-promise-object\\\/promise-states.jpg\",\"contentUrl\":\"https:\\\/\\\/assets.hongkiat.com\\\/uploads\\\/javascript-promise-object\\\/promise-states.jpg\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/javascript-promise-object\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Getting Started with JavaScript Promises\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/\",\"name\":\"Hongkiat\",\"description\":\"Tech and Design Tips\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#organization\",\"name\":\"Hongkiat.com\",\"url\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/wp-content\\\/uploads\\\/hkdc-logo-rect-yoast.jpg\",\"contentUrl\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/wp-content\\\/uploads\\\/hkdc-logo-rect-yoast.jpg\",\"width\":1200,\"height\":799,\"caption\":\"Hongkiat.com\"},\"image\":{\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/hongkiatcom\",\"https:\\\/\\\/x.com\\\/hongkiat\",\"https:\\\/\\\/www.pinterest.com\\\/hongkiat\\\/\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/#\\\/schema\\\/person\\\/e981676afae36d1ff5feb75094950ab3\",\"name\":\"Preethi Ranjit\",\"description\":\"A .NET developer with a JavaScript background, Preethi is expert in front-end coding, JavaScript, HTML, and CSS.\",\"url\":\"https:\\\/\\\/www.hongkiat.com\\\/blog\\\/author\\\/preethi\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Getting Started with JavaScript Promises - Hongkiat","description":"Asynchronous code is useful for performing tasks that are time-consuming but, of course, it's not devoid of cons. Async code uses callback functions to","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.hongkiat.com\/blog\/javascript-promise-object\/","og_locale":"en_US","og_type":"article","og_title":"Getting Started with JavaScript Promises","og_description":"Asynchronous code is useful for performing tasks that are time-consuming but, of course, it's not devoid of cons. Async code uses callback functions to","og_url":"https:\/\/www.hongkiat.com\/blog\/javascript-promise-object\/","og_site_name":"Hongkiat","article_publisher":"https:\/\/www.facebook.com\/hongkiatcom","article_published_time":"2019-04-08T15:29:09+00:00","article_modified_time":"2022-10-09T13:34:26+00:00","og_image":[{"url":"https:\/\/assets.hongkiat.com\/uploads\/javascript-promise-object\/promise-states.jpg","type":"","width":"","height":""}],"author":"Preethi Ranjit","twitter_card":"summary_large_image","twitter_creator":"@hongkiat","twitter_site":"@hongkiat","twitter_misc":{"Written by":"Preethi Ranjit","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.hongkiat.com\/blog\/javascript-promise-object\/#article","isPartOf":{"@id":"https:\/\/www.hongkiat.com\/blog\/javascript-promise-object\/"},"author":{"name":"Preethi Ranjit","@id":"https:\/\/www.hongkiat.com\/blog\/#\/schema\/person\/e981676afae36d1ff5feb75094950ab3"},"headline":"Getting Started with JavaScript Promises","datePublished":"2019-04-08T15:29:09+00:00","dateModified":"2022-10-09T13:34:26+00:00","mainEntityOfPage":{"@id":"https:\/\/www.hongkiat.com\/blog\/javascript-promise-object\/"},"wordCount":847,"commentCount":2,"publisher":{"@id":"https:\/\/www.hongkiat.com\/blog\/#organization"},"image":{"@id":"https:\/\/www.hongkiat.com\/blog\/javascript-promise-object\/#primaryimage"},"thumbnailUrl":"https:\/\/assets.hongkiat.com\/uploads\/javascript-promise-object\/promise-states.jpg","keywords":["Javascripts","Web Developers"],"articleSection":["Coding"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.hongkiat.com\/blog\/javascript-promise-object\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.hongkiat.com\/blog\/javascript-promise-object\/","url":"https:\/\/www.hongkiat.com\/blog\/javascript-promise-object\/","name":"Getting Started with JavaScript Promises - Hongkiat","isPartOf":{"@id":"https:\/\/www.hongkiat.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.hongkiat.com\/blog\/javascript-promise-object\/#primaryimage"},"image":{"@id":"https:\/\/www.hongkiat.com\/blog\/javascript-promise-object\/#primaryimage"},"thumbnailUrl":"https:\/\/assets.hongkiat.com\/uploads\/javascript-promise-object\/promise-states.jpg","datePublished":"2019-04-08T15:29:09+00:00","dateModified":"2022-10-09T13:34:26+00:00","description":"Asynchronous code is useful for performing tasks that are time-consuming but, of course, it's not devoid of cons. Async code uses callback functions to","breadcrumb":{"@id":"https:\/\/www.hongkiat.com\/blog\/javascript-promise-object\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.hongkiat.com\/blog\/javascript-promise-object\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.hongkiat.com\/blog\/javascript-promise-object\/#primaryimage","url":"https:\/\/assets.hongkiat.com\/uploads\/javascript-promise-object\/promise-states.jpg","contentUrl":"https:\/\/assets.hongkiat.com\/uploads\/javascript-promise-object\/promise-states.jpg"},{"@type":"BreadcrumbList","@id":"https:\/\/www.hongkiat.com\/blog\/javascript-promise-object\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.hongkiat.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Getting Started with JavaScript Promises"}]},{"@type":"WebSite","@id":"https:\/\/www.hongkiat.com\/blog\/#website","url":"https:\/\/www.hongkiat.com\/blog\/","name":"Hongkiat","description":"Tech and Design Tips","publisher":{"@id":"https:\/\/www.hongkiat.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.hongkiat.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.hongkiat.com\/blog\/#organization","name":"Hongkiat.com","url":"https:\/\/www.hongkiat.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.hongkiat.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/www.hongkiat.com\/blog\/wp-content\/uploads\/hkdc-logo-rect-yoast.jpg","contentUrl":"https:\/\/www.hongkiat.com\/blog\/wp-content\/uploads\/hkdc-logo-rect-yoast.jpg","width":1200,"height":799,"caption":"Hongkiat.com"},"image":{"@id":"https:\/\/www.hongkiat.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/hongkiatcom","https:\/\/x.com\/hongkiat","https:\/\/www.pinterest.com\/hongkiat\/"]},{"@type":"Person","@id":"https:\/\/www.hongkiat.com\/blog\/#\/schema\/person\/e981676afae36d1ff5feb75094950ab3","name":"Preethi Ranjit","description":"A .NET developer with a JavaScript background, Preethi is expert in front-end coding, JavaScript, HTML, and CSS.","url":"https:\/\/www.hongkiat.com\/blog\/author\/preethi\/"}]}},"jetpack_featured_media_url":"https:\/\/","jetpack_shortlink":"https:\/\/wp.me\/p4uxU-7HN","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/posts\/29623","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/users\/145"}],"replies":[{"embeddable":true,"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/comments?post=29623"}],"version-history":[{"count":2,"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/posts\/29623\/revisions"}],"predecessor-version":[{"id":62594,"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/posts\/29623\/revisions\/62594"}],"wp:attachment":[{"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/media?parent=29623"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/categories?post=29623"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/tags?post=29623"},{"taxonomy":"topic","embeddable":true,"href":"https:\/\/www.hongkiat.com\/blog\/wp-json\/wp\/v2\/topic?post=29623"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}