diff options
Diffstat (limited to 'files/es/learn/javascript/asynchronous/async_await/index.html')
-rw-r--r-- | files/es/learn/javascript/asynchronous/async_await/index.html | 411 |
1 files changed, 0 insertions, 411 deletions
diff --git a/files/es/learn/javascript/asynchronous/async_await/index.html b/files/es/learn/javascript/asynchronous/async_await/index.html deleted file mode 100644 index 3487b11664..0000000000 --- a/files/es/learn/javascript/asynchronous/async_await/index.html +++ /dev/null @@ -1,411 +0,0 @@ ---- -title: Haciendo la programación asíncrona más fácil con async y await -slug: Learn/JavaScript/Asynchronous/Async_await -translation_of: Learn/JavaScript/Asynchronous/Async_await ---- -<div>{{LearnSidebar}}</div> - -<div>{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Promises", "Learn/JavaScript/Asynchronous/Choosing_the_right_approach", "Learn/JavaScript/Asynchronous")}}</div> - -<p class="summary">Las incorporaciones más recientes al lenguaje JavaScript, son las <a href="/en-US/docs/Web/JavaScript/Reference/Statements/async_function">funciones async</a> y la palabra clave <code>await</code>, parte de la edición ECMAScript 2017 (véase <a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_Next_support_in_Mozilla">ECMAScript Next support in Mozilla</a>). Estas características, básicamente, actúan como azúcar sintáctico, haciendo el código asíncrono fácil de escribir y leer más tarde. Hacen que el código asíncrono se parezca más al código síncrono de la vieja escuela, por lo que merece la pena aprenderlo. </p> - -<p>Este artículo le da lo que usted necesita saber. </p> - -<table class="learn-box standard-table"> - <tbody> - <tr> - <th scope="row">Requisitos previos:</th> - <td>Conocimientos básicos de informática, entender de manera razonable los fundamentos de JavaScript y entender el código asíncrono en general y las promesas. </td> - </tr> - <tr> - <th scope="row">Objetivo:</th> - <td>Entender las promesas y cómo usarlas</td> - </tr> - </tbody> -</table> - -<h2 id="Los_fundamentos_de_asyncawait">Los fundamentos de async/await</h2> - -<p>Hay dos partes a la hora de usar async/await en su código.</p> - -<h3 id="La_palabra_clave_async">La palabra clave async</h3> - -<p>Primero tenemos la palabra clave "async", que se coloca delante de la declaración de una función, para convertirla en función "async"(asíncrona). Una función "async", es una función que sabe cómo esperar la posibilidad de que la palabra clave "await" sea utilizada para invocar código asíncrono. </p> - -<p>Intenta escribir las siguientes líneas en la consola de tu navegador. </p> - -<pre class="brush: js notranslate">function hello() { return "Hello" }; -hello();</pre> - -<p>La función returna "Hello" — nada especial, verdad?</p> - -<p>Pero, qué pasa si convertimos esto en una función async? Trata lo siguiente:</p> - -<pre class="brush: js notranslate">async function hello() { return "Hello" }; -hello();</pre> - -<p>Ah!. Ahora cuando invocamos la función, retorna una promesa(promise). Esta es una de las características particulares de las funciones async — los valores que retornan están garantizados para ser convertidos en promesas.</p> - -<p>También puedes crear una <a href="/en-US/docs/Web/JavaScript/Reference/Operators/async_function">expresión de función async</a>, así:</p> - -<pre class="brush: js notranslate">let hello = async function() { return "Hello" }; -hello();</pre> - -<p>Y puedes utilizar funciones flecha(arrow functions):</p> - -<pre class="brush: js notranslate">let hello = async () => { return "Hello" };</pre> - -<p>Todos estos hacen básicamente lo mismo.</p> - -<p>Para realmente consumir el valor retornado cuando la promesa se cumple, ya que se está devolviendo una promesa, podemos utilizar un bloque <code>then()</code>: </p> - -<pre class="brush: js notranslate">hello().then((value) => console.log(value))</pre> - -<p>o incluso sólo un shorthand como</p> - -<pre class="brush: js notranslate">hello().then(console.log)</pre> - -<p>Como vimos en el último artículo.</p> - -<p>La palabra clave <code>async</code> se añade a las funciones para decirles que devuelvan una promesa en lugar de devolver directamente el valor. Adicionamente, esto permite que las funciones síncronas eviten cualquier potencial sobrecarga que viene con correr con el soporte por usar <code>async</code>. Cuando una función es declarada <code>async</code> con sólo añadir la manipulación necesaria, el motor de JavaScript puede optimizar su programa por usted. Dulce!</p> - -<p>So the <code>async</code> keyword is added to functions to tell them to return a promise rather than directly returning the value. In addition, this lets synchronous functions avoid any potential overhead that comes with running with support for using <code>await</code>. By only adding the necessary handling when the function is declared <code>async</code>, the JavaScript engine can optimize your program for you. Sweet!</p> - -<h3 id="La_palabra_clave_await">La palabra clave await</h3> - -<p>La ventaja real de las funciones asincronas aparecen cuando las combinas con la palabra clave <a href="/en-US/docs/Web/JavaScript/Reference/Operators/await">await</a> — en efecto, <strong><code>await</code> solo trabaja dentro de las funciones async</strong>. Esta puede ser puesta frente a cualquier funcion async basada en una promesa para pausar tu codigo en esa linea hasta que se cumpla la promesa, entonces retorna el valor resultante. Mientras tanto, otro código que puede estar esperando una oportunidad para ejecutarse, puede hacerlo.</p> - -<p>Puedes usar <code>await</code> cuando llames cualquier funcion que retorna una Promesa, incluyendo funciones web API.</p> - -<p>Este es un ejemplo trivial:</p> - -<pre class="brush: js notranslate">async function hello() { - return greeting = await Promise.resolve("Hello"); -}; - -hello().then(alert);</pre> - -<p>Por supuesto, el ejemplo anterior no es muy util, aunque este sirve para ilustrar la syntaxis. Vamos a ver un ejemplo real.</p> - -<h2 id="Reescribiendo_el_código_de_las_promesas_con_asyncawait">Reescribiendo el código de las promesas con async/await</h2> - -<p>Let's look back at a simple fetch example that we saw in the previous article:</p> - -<pre class="brush: js notranslate">fetch('coffee.jpg') -.then(response => { - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } else { - return response.blob(); - } -}) -.then(myBlob => { - let objectURL = URL.createObjectURL(myBlob); - let image = document.createElement('img'); - image.src = objectURL; - document.body.appendChild(image); -}) -.catch(e => { - console.log('There has been a problem with your fetch operation: ' + e.message); -});</pre> - -<p>By now, you should have a reasonable understanding of promises and how they work, but let's convert this to use async/await to see how much simpler it makes things:</p> - -<pre class="brush: js notranslate">async function myFetch() { - let response = await fetch('coffee.jpg'); - - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } else { - let myBlob = await response.blob(); - - let objectURL = URL.createObjectURL(myBlob); - let image = document.createElement('img'); - image.src = objectURL; - document.body.appendChild(image); - } -} - -myFetch() -.catch(e => { - console.log('There has been a problem with your fetch operation: ' + e.message); -});</pre> - -<p>It makes code much simpler and easier to understand — no more <code>.then()</code> blocks everywhere!</p> - -<p>Since an <code>async</code> keyword turns a function into a promise, you could refactor your code to use a hybrid approach of promises and await, bringing the second half of the function out into a new block to make it more flexible:</p> - -<pre class="brush: js notranslate">async function myFetch() { - let response = await fetch('coffee.jpg'); - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } else { - return await response.blob(); - } -} - -myFetch().then((blob) => { - let objectURL = URL.createObjectURL(blob); - let image = document.createElement('img'); - image.src = objectURL; - document.body.appendChild(image); -}).catch(e => console.log(e));</pre> - -<p>You can try typing in the example yourself, or running our <a href="https://mdn.github.io/learning-area/javascript/asynchronous/async-await/simple-fetch-async-await.html">live example</a> (see also the <a href="https://github.com/mdn/learning-area/blob/master/javascript/asynchronous/async-await/simple-fetch-async-await.html">source code</a>).</p> - -<h3 id="But_how_does_it_work">But how does it work?</h3> - -<p>You'll note that we've wrapped the code inside a function, and we've included the <code>async</code> keyword before the <code>function</code> keyword. This is necessary — you have to create an async function to define a block of code in which you'll run your async code; as we said earlier, <code>await</code> only works inside of async functions.</p> - -<p>Inside the <code>myFetch()</code> function definition you can see that the code closely resembles the previous promise version, but there are some differences. Instead of needing to chain a <code>.then()</code> block on to the end of each promise-based method, you just need to add an <code>await</code> keyword before the method call, and then assign the result to a variable. The <code>await</code> keyword causes the JavaScript runtime to pause your code on this line, allowing other code to execute in the meantime, until the async function call has returned its result. Once that's complete, your code continues to execute starting on the next line. For example:</p> - -<pre class="brush: js notranslate">let response = await fetch('coffee.jpg');</pre> - -<p>The response returned by the fulfilled <code>fetch()</code> promise is assigned to the <code>response</code> variable when that response becomes available, and the parser pauses on this line until that occurs. Once the response is available, the parser moves to the next line, which creates a <code><a href="/en-US/docs/Web/API/Blob">Blob</a></code> out of it. This line also invokes an async promise-based method, so we use <code>await</code> here as well. When the result of operation returns, we return it out of the <code>myFetch()</code> function.</p> - -<p>This means that when we call the <code>myFetch()</code> function, it returns a promise, so we can chain a <code>.then()</code> onto the end of it inside which we handle displaying the blob onscreen.</p> - -<p>You are probably already thinking "this is really cool!", and you are right — fewer <code>.then()</code> blocks to wrap around code, and it mostly just looks like synchronous code, so it is really intuitive.</p> - -<h3 id="Adding_error_handling">Adding error handling</h3> - -<p>And if you want to add error handling, you've got a couple of options.</p> - -<p>You can use a synchronous <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch">try...catch</a></code> structure with <code>async</code>/<code>await</code>. This example expands on the first version of the code we showed above:</p> - -<pre class="brush: js notranslate">async function myFetch() { - try { - let response = await fetch('coffee.jpg'); - - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } else { - let myBlob = await response.blob(); - let objectURL = URL.createObjectURL(myBlob); - let image = document.createElement('img'); - image.src = objectURL; - document.body.appendChild(image); - } - } catch(e) { - console.log(e); - } -} - -myFetch();</pre> - -<p>The <code>catch() {}</code> block is passed an error object, which we've called <code>e</code>; we can now log that to the console, and it will give us a detailed error message showing where in the code the error was thrown.</p> - -<p>If you wanted to use the second (refactored) version of the code that we showed above, you would be better off just continuing the hybrid approach and chaining a <code>.catch()</code> block onto the end of the <code>.then()</code> call, like this:</p> - -<pre class="brush: js notranslate">async function myFetch() { - let response = await fetch('coffee.jpg'); - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } else { - return await response.blob(); - } -} - -myFetch().then((blob) => { - let objectURL = URL.createObjectURL(blob); - let image = document.createElement('img'); - image.src = objectURL; - document.body.appendChild(image); -}) -.catch((e) => - console.log(e) -);</pre> - -<p>This is because the <code>.catch()</code> block will catch errors occurring in both the async function call and the promise chain. If you used the <code>try</code>/<code>catch</code> block here, you might still get unhandled errors in the <code>myFetch()</code> function when it's called.</p> - -<p>You can find both of these examples on GitHub:</p> - -<ul> - <li><a href="https://mdn.github.io/learning-area/javascript/asynchronous/async-await/simple-fetch-async-await-try-catch.html">simple-fetch-async-await-try-catch.html</a> (see <a href="https://github.com/mdn/learning-area/blob/master/javascript/asynchronous/async-await/simple-fetch-async-await-try-catch.html">source code</a>)</li> - <li><a href="https://mdn.github.io/learning-area/javascript/asynchronous/async-await/simple-fetch-async-await-promise-catch.html">simple-fetch-async-await-promise-catch.html</a> (see <a href="https://github.com/mdn/learning-area/blob/master/javascript/asynchronous/async-await/simple-fetch-async-await-promise-catch.html">source code</a>)</li> -</ul> - -<h2 id="Awaiting_a_Promise.all">Awaiting a Promise.all()</h2> - -<p>async/await is built on top of <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">promises</a>, so it's compatible with all the features offered by promises. This includes <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all">Promise.all()</a></code> — you can quite happily await a <code>Promise.all()</code> call to get all the results returned into a variable in a way that looks like simple synchronous code. Again, let's return to <a href="https://github.com/mdn/learning-area/blob/master/javascript/asynchronous/promises/promise-all.html">an example we saw in our previous article</a>. Keep it open in a separate tab so you can compare and contrast with the new version shown below.</p> - -<p>Converting this to async/await (see <a href="https://mdn.github.io/learning-area/javascript/asynchronous/async-await/promise-all-async-await.html">live demo</a> and <a href="https://github.com/mdn/learning-area/blob/master/javascript/asynchronous/async-await/promise-all-async-await.html">source code</a>), this now looks like so:</p> - -<pre class="brush: js notranslate">async function fetchAndDecode(url, type) { - let response = await fetch(url); - - let content; - - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } else { - if(type === 'blob') { - content = await response.blob(); - } else if(type === 'text') { - content = await response.text(); - } - - return content; - } - -} - -async function displayContent() { - let coffee = fetchAndDecode('coffee.jpg', 'blob'); - let tea = fetchAndDecode('tea.jpg', 'blob'); - let description = fetchAndDecode('description.txt', 'text'); - - let values = await Promise.all([coffee, tea, description]); - - let objectURL1 = URL.createObjectURL(values[0]); - let objectURL2 = URL.createObjectURL(values[1]); - let descText = values[2]; - - let image1 = document.createElement('img'); - let image2 = document.createElement('img'); - image1.src = objectURL1; - image2.src = objectURL2; - document.body.appendChild(image1); - document.body.appendChild(image2); - - let para = document.createElement('p'); - para.textContent = descText; - document.body.appendChild(para); -} - -displayContent() -.catch((e) => - console.log(e) -);</pre> - -<p>You'll see that the <code>fetchAndDecode()</code> function has been converted easily into an async function with just a few changes. See the <code>Promise.all()</code> line:</p> - -<pre class="brush: js notranslate">let values = await Promise.all([coffee, tea, description]);</pre> - -<p>By using <code>await</code> here we are able to get all the results of the three promises returned into the <code>values</code> array, when they are all available, in a way that looks very much like sync code. We've had to wrap all the code in a new async function, <code>displayContent()</code>, and we've not reduced the code by a lot of lines, but being able to move the bulk of the code out of the <code>.then()</code> block provides a nice, useful simplification, leaving us with a much more readable program.</p> - -<p>For error handling, we've included a <code>.catch()</code> block on our <code>displayContent()</code> call; this will handle errors ocurring in both functions.</p> - -<div class="blockIndicator note"> -<p><strong>Note</strong>: It is also possible to use a sync <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#The_finally_clause">finally</a></code> block within an async function, in place of a <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally">.finally()</a></code> async block, to show a final report on how the operation went — you can see this in action in our <a href="https://mdn.github.io/learning-area/javascript/asynchronous/async-await/promise-finally-async-await.html">live example</a> (see also the <a href="https://github.com/mdn/learning-area/blob/master/javascript/asynchronous/async-await/promise-finally-async-await.html">source code</a>).</p> -</div> - -<h2 id="The_downsides_of_asyncawait">The downsides of async/await</h2> - -<p>Async/await is really useful to know about, but there are a couple of downsides to consider.</p> - -<p>Async/await makes your code look synchronous, and in a way it makes it behave more synchronously. The <code>await</code> keyword blocks execution of all the code that follows until the promise fulfills, exactly as it would with a synchronous operation. It does allow other tasks to continue to run in the meantime, but your own code is blocked.</p> - -<p>This means that your code could be slowed down by a significant number of awaited promises happening straight after one another. Each <code>await</code> will wait for the previous one to finish, whereas actually what you want is for the promises to begin processing simultaneously, like they would do if we weren't using async/await.</p> - -<p>There is a pattern that can mitigate this problem — setting off all the promise processes by storing the <code>Promise</code> objects in variables, and then awaiting them all afterwards. Let's have a look at some examples that prove the concept.</p> - -<p>We've got two examples available — <a href="https://mdn.github.io/learning-area/javascript/asynchronous/async-await/slow-async-await.html">slow-async-await.html</a> (see <a href="https://github.com/mdn/learning-area/blob/master/javascript/asynchronous/async-await/slow-async-await.html">source code</a>) and <a href="https://mdn.github.io/learning-area/javascript/asynchronous/async-await/fast-async-await.html">fast-async-await.html</a> (see <a href="https://github.com/mdn/learning-area/blob/master/javascript/asynchronous/async-await/fast-async-await.html">source code</a>). Both of them start off with a custom promise function that fakes an async process with a <code><a href="/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout">setTimeout()</a></code> call:</p> - -<pre class="brush: js notranslate">function timeoutPromise(interval) { - return new Promise((resolve, reject) => { - setTimeout(function(){ - resolve("done"); - }, interval); - }); -};</pre> - -<p>Then each one includes a <code>timeTest()</code> async function that awaits three <code>timeoutPromise()</code> calls:</p> - -<pre class="brush: js notranslate">async function timeTest() { - ... -}</pre> - -<p>Each one ends by recording a start time, seeing how long the <code>timeTest()</code> promise takes to fulfill, then recording an end time and reporting how long the operation took in total:</p> - -<pre class="brush: js notranslate">let startTime = Date.now(); -timeTest().then(() => { - let finishTime = Date.now(); - let timeTaken = finishTime - startTime; - alert("Time taken in milliseconds: " + timeTaken); -})</pre> - -<p>It is the <code>timeTest()</code> function that differs in each case.</p> - -<p>In the <code>slow-async-await.html</code> example, <code>timeTest()</code> looks like this:</p> - -<pre class="brush: js notranslate">async function timeTest() { - await timeoutPromise(3000); - await timeoutPromise(3000); - await timeoutPromise(3000); -}</pre> - -<p>Here we simply await all three <code>timeoutPromise()</code> calls directly, making each one alert for 3 seconds. Each subsequent one is forced to wait until the last one finished — if you run the first example, you'll see the alert box reporting a total run time of around 9 seconds.</p> - -<p>In the <code>fast-async-await.html</code> example, <code>timeTest()</code> looks like this:</p> - -<pre class="brush: js notranslate">async function timeTest() { - const timeoutPromise1 = timeoutPromise(3000); - const timeoutPromise2 = timeoutPromise(3000); - const timeoutPromise3 = timeoutPromise(3000); - - await timeoutPromise1; - await timeoutPromise2; - await timeoutPromise3; -}</pre> - -<p>Here we store the three <code>Promise</code> objects in variables, which has the effect of setting off their associated processes all running simultaneously.</p> - -<p>Next, we await their results — because the promises all started processing at essentially the same time, the promises will all fulfill at the same time; when you run the second example, you'll see the alert box reporting a total run time of just over 3 seconds!</p> - -<p>You'll have to test your code carefully, and bear this in mind if performance starts to suffer.</p> - -<p>Another minor inconvenience is that you have to wrap your awaited promises inside an async function.</p> - -<h2 id="Asyncawait_class_methods">Async/await class methods</h2> - -<p>As a final note before we move on, you can even add <code>async</code> in front of class/object methods to make them return promises, and <code>await</code> promises inside them. Take a look at the <a href="/en-US/docs/Learn/JavaScript/Objects/Inheritance#ECMAScript_2015_Classes">ES class code we saw in our object-oriented JavaScript article</a>, and then look at our modified version with an <code>async</code> method:</p> - -<pre class="brush: js notranslate">class Person { - constructor(first, last, age, gender, interests) { - this.name = { - first, - last - }; - this.age = age; - this.gender = gender; - this.interests = interests; - } - - async greeting() { - return await Promise.resolve(`Hi! I'm ${this.name.first}`); - }; - - farewell() { - console.log(`${this.name.first} has left the building. Bye for now!`); - }; -} - -let han = new Person('Han', 'Solo', 25, 'male', ['Smuggling']);</pre> - -<p>The first class method could now be used something like this:</p> - -<pre class="brush: js notranslate">han.greeting().then(console.log);</pre> - -<h2 id="Browser_support">Browser support</h2> - -<p>One consideration when deciding whether to use async/await is support for older browsers. They are available in modern versions of most browsers, the same as promises; the main support problems come with Internet Explorer and Opera Mini.</p> - -<p>If you want to use async/await but are concerned about older browser support, you could consider using the <a href="https://babeljs.io/">BabelJS</a> library — this allows you to write your applications using the latest JavaScript and let Babel figure out what changes if any are needed for your user’s browsers. On encountering a browser that does not support async/await, Babel's polyfill can automatically provide fallbacks that work in older browsers.</p> - -<h2 id="Conclusion">Conclusion</h2> - -<p>And there you have it — async/await provide a nice, simplified way to write async code that is simpler to read and maintain. Even with browser support being more limited than other async code mechanisms at the time of writing, it is well worth learning and considering for use, both for now and in the future.</p> - -<p>{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Promises", "Learn/JavaScript/Asynchronous/Choosing_the_right_approach", "Learn/JavaScript/Asynchronous")}}</p> - -<h2 id="In_this_module">In this module</h2> - -<ul> - <li><a href="/en-US/docs/Learn/JavaScript/Asynchronous/Concepts">General asynchronous programming concepts</a></li> - <li><a href="/en-US/docs/Learn/JavaScript/Asynchronous/Introducing">Introducing asynchronous JavaScript</a></li> - <li><a href="/en-US/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals">Cooperative asynchronous JavaScript: Timeouts and intervals</a></li> - <li><a href="/en-US/docs/Learn/JavaScript/Asynchronous/Promises">Graceful asynchronous programming with Promises</a></li> - <li><a href="/en-US/docs/Learn/JavaScript/Asynchronous/Async_await">Making asynchronous programming easier with async and await</a></li> - <li><a href="/en-US/docs/Learn/JavaScript/Asynchronous/Choosing_the_right_approach">Choosing the right approach</a></li> -</ul> |