On our journey of developing an app that will change the automotive landscape we also want to educate our community on certain software engineering paradigms. To start this series of blog posts that will discus anything from optimizing performance, story telling, difficult obstacles we’ve overcome and more, we’re going to dive into javascript promises.
On the surface javascript promises can seem kind of daunting. how come I can use .then
or async await
? whats the difference? Can I run promises together? In this article we can answer those questions and maybe encouraging you to start your own javascript project.
The
MDN Web DocsPromise
object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Picture a promise as its name suggests—an assurance that an outcome will eventually come, That could be a returned value or an error thrown. How can we navigate the concept of “eventuality” in code? To tackle such scenarios, we use specific methodologies. It’s not just about understanding the definition; it’s about harnessing the potential of promises to enhance application performance. So, let’s delve into the practical applications of promises, unlocking their capabilities and empowering you to wield them adeptly in your coding endeavors.
Enough words, let’s look at some examples and I’ll walk you through what they mean and why they’re significant.
Create a Promise
In this example we are creating a simple function in javascript that is a promise. We will be using this function throughout the examples as a promise. All this function does is return a promise that will eventually resolve or reject into a string after 1000 ms (1 second)
const fetchData = () => {
return new Promise((resolve, reject) => {
// Simulating an asynchronous operation (e.g., fetching data from an API)
setTimeout(() => {
const success = true; // Set to false to simulate failure
if (success) {
resolve('Data successfully fetched!');
} else {
reject('Error: Unable to fetch data!');
}
}, 1000); // Simulating a delay of 1 second
});
};
Promise Chaining using “.then”
Using .then
is a great way to single single promises. In this example we call the previously mentioned function fetchData
and wait for it to reject or resolve by using .then
. The result
is the string mentioned in the fetchData
function.
// Consuming the Promise using .then()
fetchData()
.then((result) => {
console.log(result); // Output: Data successfully fetched!
})
.catch((error) => {
console.error(error); // Output: Error: Unable to fetch data!
});
Seems easy enough right? What happens when we need to fetch data from a lot of sources and they depend on each other? If we used promise chaining it might look like this:
// Consuming the Promise using .then()
fetchData()
.then((result) => {
fetchMoreData(result).then((result_2) => {
fetchEvenMoreData(result_2).then((result_3) => {
console.log("this is getting pretty ugly");
})
.catch((error) => {
console.error("fetchEvenMoreData Error: ",error);
});
})
.catch((error) => {
console.error("fetchMoreData Error: ",error);
});
})
.catch((error) => {
console.error("fetchData Error:", error);
});
That’s getting pretty messy. The last thing we want is to debug something that looks like this. Maybe we should try using async await
instead
Async await
Using the previous fetchData
function lets implement the same thing but using a new methodology called async await
const fetchDataAsync = async () => {
try {
// Utilizing async/await for a more synchronous-looking code
const result = await fetchData();
console.log(result); // Output: Data successfully fetched!
} catch (error) {
console.error(error); // Output: Error: Unable to fetch data!
}
};
fetchDataAsync();
I would say that looks a lot cleaner and easier to read. But what if we want to call multiple fetchData
functions and they depend on each other?
const fetchDataAsync = async () => {
try {
// Utilizing async/await for a more synchronous-looking code
const result = await fetchData();
const result_2 = await fetchMoreData(result);
const result_3 = await fetchEvenMoreData(result_2);
console.log(result_3); // Output: Data successfully fetched!
} catch (error) {
console.error(error); // Output: Error: Unable to fetch data!
}
};
fetchDataAsync();
I can read that a lot easier than the promise chaining example. But what if I want to query a bunch of resources that are not dependent on each other?
const fetchDataConcurrently = async () => {
try {
// Creating an array of promises
const requests = Array.from({ length: 3 }, (_, index) => fetchData());
// Using Promise.all to fetch data concurrently
const results = await Promise.all(requests);
// Logging the results
results.forEach((result, index) => {
console.log(`Request ${index + 1}: ${result}`);
});
} catch (error) {
console.error(error); // Output: Error: Unable to fetch data!
}
};
// Invoking the async function to fetch data concurrently
fetchDataConcurrently();
Using Promise.all
allows use to run multiple requests concurrently. That means fetchData()
is run all at the same time instead of waiting for each call to finish. Switching from promise chaining to using async await can improve performance significantly now that we don’t have to wait for one promise to result before calling the second one.
Your turn!
Now that we’ve scratched the surface of JavaScript promises, it’s time for you to dive in and learn more about their potential in your projects. Embrace the power of asynchronous operations, knowing that promises provide a structured and elegant solution to handling tasks that take time.
As you embark on your coding journey, don’t be afraid to experiment with promises. Whether you choose the traditional .then
approach or opt for the cleaner async/await
syntax, the goal is to make your code more readable and maintainable.
Remember, every developer encounters challenges when working with asynchronous code, and that’s absolutely okay! It’s part of the learning process. Take this newfound knowledge, start small, and gradually incorporate promises into your projects. As you gain confidence, you’ll find yourself navigating the intricacies of asynchronous programming with ease.
Leave a Reply