Asynchronous programming has become a prevailing need in the world of web programming, especially when handling time-consuming tasks such as network requests, file access, or any operation that does not provide immediate results. JavaScript offers several ways to handle asynchronous operations, and two of them are Promises and the Async/Await paradigm. Let's delve deeper with practical examples to understand how to apply these powerful tools in your projects.
Table of Contents
ToggleUnderstanding Promises in JavaScript
Promises are objects that represent the eventual completion (or failure) of an asynchronous operation. A promise can be in one of three states:
- Pending: The initial state, where the promise waits for an asynchronous operation.
- Fulfilled: It means that the operation was completed satisfactorily.
- Rejected: The operation failed for some reason.
Examples with Promises
Let's start with some examples using Promises:
Load a resource asynchronously
function cargarRecurso(url) {
return new Promise((resolve, reject) => {
const httpRequest = new XMLHttpRequest();
httpRequest.open('GET', url);
httpRequest.onload = () => {
if (httpRequest.status === 200) {
resolve(httpRequest.responseText);
} else {
reject(new Error(httpRequest.statusText));
}
};
httpRequest.onerror = () => {
reject(new Error('Error en la solicitud de red'));
};
httpRequest.send();
});
}
cargarRecurso('https://api.miweb.com/datos')
.then(datos => {
console.log('Datos cargados:', datos);
})
.catch(error => {
console.error('Falló la carga del recurso:', error);
});
Promise Chaining
Promises can be chained to perform tasks in sequence.
function processData(data) { return new Promise((resolve, reject) => { try { const processed = data.map(item => item.toUpperCase()); resolve(processed); } catch (error) { reject( mistake); } }); } loadResource('https://api.miweb.com/datos') .then(data => processData(JSON.parse(data))) .then(processeddata => { console.log('processed data: ', processedData); }) .catch(error => { console.error('There was an error in the promise chain:', error); });
Async/Await: Elegant Syntax for Asynchrony
With the introduction of async
y await
In ECMAScript 2017, JavaScript simplified working with asynchronous operations, allowing us to write asynchronous code in a more synchronous-like style.
Examples with Async/Await
Let's rewrite the previous examples using async
y await
.
Load a resource with Async/Await
async function loadAsyncResource(url) { try { const response = await fetch(url); if (!response.ok) throw new Error(response.statusText); return await response.text(); } catch (error) { console.error('Loading resource failed:', error); throwerror; // We propagate the error } } async function main() { try { const data = await loadRecursoAsync('https://api.miweb.com/datos'); console.log('Data loaded with async/await:', data); } catch (error) { // Error handling } } main();
Chaining and Error Handling with Async/Await
With async/await
, chaining operations is as simple as writing instructions one after another, and error handling is done with blocks try/catch
.
async function processAsyncData(data) { return data.map(item => item.toUpperCase()); } async function mainProcessing() { try { const data = await loadAsyncResource('https://api.miweb.com/datos'); const processedData = await processAsyncData(JSON.parse(data)); console.log('Data processed with async/await:', dataProcessed); } catch (error) { console.error('Error during data processing:', error); } } mainProcessing();
Advantages of Async/Await over Promises
- Cleaner syntax- Less code, more readable and less error-prone.
- More intuitive error handling: used
try
ycatch
as if it were synchronous code. - Better control flow: ease of using loops, conditionals and other control structures.
Conclusion
Whether with Promises or Async/Await, JavaScript offers flexibility and power to handle asynchrony. Promises provide a structured way of working with operations that will take time to complete, while Async/Await offers a more elegant and easy-to-understand syntax, making asynchronous programming feel as natural as writing synchronous code.
Remember to practice these concepts and apply them in your projects to become a more competent and efficient web developer. And if you have any questions or want to share your experiences with the community, don't hesitate to visit my blog or put you in contact. Keep programming and learning every day!