{"id":757,"date":"2024-07-30T20:46:31","date_gmt":"2024-07-30T18:46:31","guid":{"rendered":"https:\/\/blog.sutilweb.eu\/?page_id=757"},"modified":"2024-07-30T20:46:32","modified_gmt":"2024-07-30T18:46:32","slug":"003-callbacks-javascript","status":"publish","type":"page","link":"https:\/\/sutilweb.eu\/index.php\/lenguajes\/javascript\/javascript-practico\/08-programacion-asincrona\/003-callbacks-javascript\/","title":{"rendered":"003. Callbacks Javascript"},"content":{"rendered":"\n<p>En el cap\u00edtulo anterior ve\u00edamos como trabaja el <strong>Event loop<\/strong> en <strong>Javascript<\/strong>, las caracter\u00edsticas de la <strong>asincron\u00eda<\/strong>, donde vamos a tener <strong>operaciones de entrada y salida<\/strong> en un s\u00f3lo <strong>hilo de procesos<\/strong>, ya que <strong>Javascript<\/strong> es un lenguaje <strong>Single thread<\/strong>, y la manera en que se est\u00e1n apilando las tareas, estas tareas van a ser <strong>as\u00edncronas<\/strong>, es decir, no esperan resolverse en el presente inmediato sino en el futuro, y no son <strong>bloqueantes<\/strong>, es decir, no se van a esperar y van a detener el flujo del programa o aplicaci\u00f3n mientras retorna su respuesta, sino que inmediatamente que se ejecutan, van a regresar el control al <strong>hilo principal<\/strong> del programa, y en el momento que la respuesta est\u00e9 lista enviar\u00e1n una notificaci\u00f3n y se ejecutar\u00e1 el resultado.<\/p>\n\n\n\n<!--more-->\n\n\n\n<h2 class=\"wp-block-heading\">Mecanismos para trabajar la asincron\u00eda<\/h2>\n\n\n\n<p>Para trabajar la <strong>asincron\u00eda<\/strong>, <strong>Javascript<\/strong> dispone de diferentes mecanismos que son los que vamos a ver en los siguientes cap\u00edtulos.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Callbacks<\/h2>\n\n\n\n<p>El primer mecanismo que vamos a ver son las <strong>Callbacks<\/strong>. Una <strong>Callback<\/strong> o <strong>llamada de vueltas<\/strong> es una <strong>funci\u00f3n<\/strong> que se va a ejecutar despu\u00e9s de que otra lo haga, de hecho es el mecanismo por excelencia que tiene <strong>Javascript<\/strong> incluso para invocar algunas de sus <strong>funciones<\/strong>.<\/p>\n\n\n\n<p>Hay que recordar, como vimos en cap\u00edtulos pasados, que las <strong>funciones<\/strong> son <strong>ciudadanos de primer orden<\/strong>, porque con las <strong>funciones<\/strong> podemos hacer de todo, como simular la orientaci\u00f3n de objetos a trav\u00e9s de <strong>funciones constructoras<\/strong>, retornar una <strong>funci\u00f3n<\/strong> como el valor de retorno de otra, podemos pasar como par\u00e1metros <strong>funciones<\/strong>, crear <strong>funciones autoinvocadas<\/strong>, <strong>an\u00f3nimas<\/strong>&#8230; Las <strong>funciones<\/strong> juegan un rol muy principal en la programaci\u00f3n con <strong>Javascript<\/strong>, y el <strong>Callback<\/strong> es el primer mecanismo que tiene <strong>Javascript<\/strong> para poder trabajar con la <strong>asincron\u00eda<\/strong>.<\/p>\n\n\n\n<p>Imaginemos que necesitamos trabajar varias <strong>Callbacks<\/strong> anidadas, \u00e9sto va a generar lo que se conoce como <strong>Callback Hell<\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Como trabaja una Callback<\/h2>\n\n\n\n<p>Vamos a hacer un ejm de c\u00f3digo <strong>Javascript<\/strong> utilizando lo que se denomina <strong>recursividad<\/strong>, que es&nbsp; que la funci\u00f3n se invoca a s\u00ed misma dentro de s\u00ed, y esto es lo que va a ir generando el <strong>Callback<\/strong>.<\/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;Asincron\u00eda - Callbacks&lt;\/title&gt;\n&nbsp; &lt;\/head&gt;\n\n&nbsp; &lt;body&gt;\n&nbsp; &nbsp; &lt;h1&gt;Asincron\u00eda - Callbacks&lt;\/h1&gt;\n\n&nbsp; &nbsp; &lt;script&gt;\n&nbsp; &nbsp; &nbsp; function cuadradoCallback(value, callback) {\n&nbsp; &nbsp; &nbsp; &nbsp; setTimeout(() =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; callback(value, value * value);\n&nbsp; &nbsp; &nbsp; &nbsp; }, 0 || Math.random() * 100);\n&nbsp; &nbsp; &nbsp; }\n\n&nbsp; &nbsp; &nbsp; cuadradoCallback(0, (value, result) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; console.log(\"Inicio callback\");\n&nbsp; &nbsp; &nbsp; &nbsp; console.log(`Callback: ${value}: ${result}`);\n&nbsp; &nbsp; &nbsp; &nbsp; cuadradoCallback(1, (value, result) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(`Callback: ${value}: ${result}`);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cuadradoCallback(2, (value, result) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(`Callback: ${value}, ${result}`);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });\n&nbsp; &nbsp; &nbsp; &nbsp; });\n&nbsp; &nbsp; &nbsp; });\n&nbsp; &nbsp; &lt;\/script&gt;\n&nbsp; &lt;\/body&gt;\n&lt;\/html&gt;<\/pre>\n\n\n\n<p>Las <strong>Callback<\/strong> nos sirven para controlar los pasos que ha de llevar el c\u00f3digo, y que no se salte un c\u00f3digo antes que otro. En el ejm de arriba, el siguiente n\u00famero no se ejecuta hasta que no ha terminado el anterior. El <strong>Callback<\/strong> es el primer mecanismo que tenemos para controlar la <strong>asincron\u00eda<\/strong>, es decir, para todo lo que se espera en nuestra aplicaci\u00f3n que vaya funcionando paso a paso, tengamos ese control y no se vayan perdiendo cosas por el camino.<\/p>\n\n\n\n<p>El camino a mejorar una estructura de <strong>Callback<\/strong> en un <strong>c\u00f3digo as\u00edncrono<\/strong> es <strong>modularizar<\/strong> y utilizar las <strong>promesas<\/strong>, los <strong>generadores<\/strong> o las <strong>funciones as\u00edncronas<\/strong>, que son los siguientes mecanismos dentro de la <strong>asincron\u00eda<\/strong> en <strong>Javascript<\/strong> que veremos en los proximos cap\u00edtulos.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>En el cap\u00edtulo anterior ve\u00edamos como trabaja el Event loop en Javascript, las caracter\u00edsticas de la asincron\u00eda, donde vamos a [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":746,"menu_order":2,"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-757","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":"En el cap\u00edtulo anterior ve\u00edamos como trabaja el Event loop en Javascript, las caracter\u00edsticas de la asincron\u00eda, donde vamos a [&hellip;]","_links":{"self":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/757","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=757"}],"version-history":[{"count":2,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/757\/revisions"}],"predecessor-version":[{"id":759,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/757\/revisions\/759"}],"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=757"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}