{"id":760,"date":"2024-07-30T20:47:32","date_gmt":"2024-07-30T18:47:32","guid":{"rendered":"https:\/\/blog.sutilweb.eu\/?page_id=760"},"modified":"2024-07-30T20:47:33","modified_gmt":"2024-07-30T18:47:33","slug":"004-promesas-javascript","status":"publish","type":"page","link":"https:\/\/sutilweb.eu\/index.php\/lenguajes\/javascript\/javascript-practico\/08-programacion-asincrona\/004-promesas-javascript\/","title":{"rendered":"004. Promesas Javascript"},"content":{"rendered":"\n<p>Cuando tenemos que estar concatenando una <strong>Callback<\/strong> detr\u00e1s de otra para hacer diferentes tareas, pero que unas dependen de otras, entonces se nos empieza a generar la famosa <strong>Callback Hell<\/strong> o <strong>pir\u00e1mide del infierno<\/strong>. Adem\u00e1s, si queremos manipular el <strong>manejo de errores<\/strong> en la <strong>concatenaci\u00f3n de funciones<\/strong>, tendr\u00edamos que estar haciendo el <strong>manejo del error<\/strong> por cada <strong>funci\u00f3n<\/strong>.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>Para resolver el problema de la <strong>pir\u00e1mide del infierno<\/strong> y del <strong>manejo de errores<\/strong>, <strong>Javascript<\/strong> tiene un mecanismo denominado <strong>promesas<\/strong>, las cuales trabajan con dos recursos principales:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><em>resolve()<\/em><\/strong><\/li>\n\n\n\n<li><strong><em>reject()<\/em><\/strong><\/li>\n<\/ul>\n\n\n\n<p>Una <strong>promesa<\/strong> la tenemos que ver como un <strong><em>if&#8230; else<\/em><\/strong>. Si la <strong>promesa<\/strong> se cumple se ejecuta el <strong><em>resolve()<\/em><\/strong>. Si la promesa falla por el motivo que sea, entonces se ejecuta el <strong><em>reject()<\/em><\/strong>. Veamos el funcionamiento de las <strong>promesas<\/strong>.<\/p>\n\n\n\n<p>Cuanto tenemos una <strong>funci\u00f3n<\/strong> que devuelve una <strong>promesa<\/strong>, tenemos dos m\u00e9todos para ir trabajando la <strong>sincron\u00eda<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>M\u00e9todo <strong><em>then()<\/em><\/strong>: es el siguiente bloque que se va a ejecutar una vez se cumpla la funci\u00f3n inicial. Podemos tener tantos m\u00e9todos <strong><em>then()<\/em><\/strong> como necesitemos.<\/li>\n\n\n\n<li>M\u00e9todo <strong><em>catch()<\/em><\/strong>: Al final de todos los m\u00e9todos <strong><em>then()<\/em><\/strong> tenemos un m\u00e9todo <strong><em>catch()<\/em><\/strong>, que, como su nombre dice, va a capturar el error resultante del <strong><em>reject()<\/em><\/strong>.<\/li>\n<\/ul>\n\n\n\n<p>Las <strong>promesas<\/strong> se usan cuando ya tenemos una concatenaci\u00f3n de varios <strong>procesos as\u00edncronos<\/strong>, de lo contrario es m\u00e1s sencillo utilizar una <strong>callback<\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Ejm completo<\/h2>\n\n\n\n<p>Veamos un ejm completo<\/p>\n\n\n\n<p><strong>Ejm<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;!DOCTYPE html&gt;\n&lt;html lang=\"es\"&gt;\n&nbsp; &lt;head&gt;\n&nbsp; &nbsp; &lt;meta charset=\"UTF-8\" \/&gt;\n&nbsp; &nbsp; &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" \/&gt;\n&nbsp; &nbsp; &lt;title&gt;Promesas Javascript&lt;\/title&gt;\n&nbsp; &lt;\/head&gt;\n\n&nbsp; &lt;body&gt;\n&nbsp; &nbsp; &lt;h1&gt;Promesas Javascript&lt;\/h1&gt;\n\n&nbsp; &nbsp; &lt;script&gt;\n&nbsp; &nbsp; &nbsp; function cuadradoPromise(value) {\n&nbsp; &nbsp; &nbsp; &nbsp; if (typeof value !== \"number\")\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Promise.reject(`Error: el valor \"${value}\" no es un n\u00famero`);\n&nbsp; &nbsp; &nbsp; &nbsp; return new Promise((resolve, reject) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setTimeout(() =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve({ value, result: value * value });\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, 0 || Math.random() * 1000);\n&nbsp; &nbsp; &nbsp; &nbsp; });\n&nbsp; &nbsp; &nbsp; }\n\n&nbsp; &nbsp; &nbsp; cuadradoPromise(0)\n&nbsp; &nbsp; &nbsp; &nbsp; .then((obj) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(obj);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(\"Inicio Promise\");\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(`Promise: ${obj.value}, ${obj.result}`);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return cuadradoPromise(1);\n&nbsp; &nbsp; &nbsp; &nbsp; })\n&nbsp; &nbsp; &nbsp; &nbsp; .then((obj) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(`Promise: ${obj.value}, ${obj.result}`);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return cuadradoPromise(2);\n&nbsp; &nbsp; &nbsp; &nbsp; })\n&nbsp; &nbsp; &nbsp; &nbsp; .then((obj) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(`Promise: ${obj.value}, ${obj.result}`);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return cuadradoPromise(3);\n&nbsp; &nbsp; &nbsp; &nbsp; })\n&nbsp; &nbsp; &nbsp; &nbsp; .then((obj) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(`Promise: ${obj.value}, ${obj.result}`);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return cuadradoPromise(4);\n&nbsp; &nbsp; &nbsp; &nbsp; })\n&nbsp; &nbsp; &nbsp; &nbsp; .then((obj) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(`Promise: ${obj.value}, ${obj.result}`);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return cuadradoPromise(\"5\");\n&nbsp; &nbsp; &nbsp; &nbsp; })\n&nbsp; &nbsp; &nbsp; &nbsp; .then((obj) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(`Promise: ${obj.value}, ${obj.result}`);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(\"Fin Promise\");\n&nbsp; &nbsp; &nbsp; &nbsp; })\n&nbsp; &nbsp; &nbsp; &nbsp; .catch((err) =&gt; console.log(err));\n&nbsp; &nbsp; &lt;\/script&gt;\n&nbsp; &lt;\/body&gt;\n&lt;\/html&gt;<\/pre>\n\n\n\n<p>Muchas <strong>APIs<\/strong> externas est\u00e1n ya retornando <strong>promesas<\/strong>, por ejm, <strong>Fetch<\/strong>, que es la forma moderna de hacer <strong>Ajax<\/strong>, internamente todo lo trabaja en un <strong>objeto de promesa<\/strong>, de tal manera que para ir trabajando los datos que te devuelve una petici\u00f3n <strong>Ajax<\/strong> mediante <strong>Fetch<\/strong>, vamos a tener que estar utilizando los m\u00e9todoso <strong><em>then()<\/em><\/strong> y <strong><em>catch()<\/em><\/strong>. Si utilizamos <strong>Firebase<\/strong> para conectarnos a una <strong>base de datos<\/strong> en tiempo real, que es un servicio de <strong>Google<\/strong> creado con <strong>Javascript<\/strong>, los <strong>m\u00e9todos<\/strong> que ofrece para conectarnos a su <strong>base de datos<\/strong> o a su servicios de autenticaci\u00f3n son <strong>promesas<\/strong>, por lo que vamos a estar viendo, sobre todo en c\u00f3digo muy moderno, el uso de <strong>promesas<\/strong>. Cuando en una <strong>API<\/strong> veamos en su documentaci\u00f3n que nos va a hacer trabajar con <strong><em>then()<\/em><\/strong> y <strong><em>catch()<\/em><\/strong> es que est\u00e1 trabajando con <strong>promesas<\/strong>.<\/p>\n\n\n\n<p>En el pr\u00f3ximo cap\u00edtulo veremos lo que son las <strong>funciones as\u00edncronas<\/strong>, que no vienen a sustituir a las <strong>promesas<\/strong>, sino a trabajar juntas.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Cuando tenemos que estar concatenando una Callback detr\u00e1s de otra para hacer diferentes tareas, pero que unas dependen de otras, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":746,"menu_order":3,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"class_list":["post-760","page","type-page","status-publish","hentry"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"Sutil Web","author_link":"https:\/\/sutilweb.eu\/index.php\/author\/sutilweb\/"},"uagb_comment_info":0,"uagb_excerpt":"Cuando tenemos que estar concatenando una Callback detr\u00e1s de otra para hacer diferentes tareas, pero que unas dependen de otras, [&hellip;]","_links":{"self":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/760","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/comments?post=760"}],"version-history":[{"count":2,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/760\/revisions"}],"predecessor-version":[{"id":762,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/760\/revisions\/762"}],"up":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/746"}],"wp:attachment":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/media?parent=760"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}