2. Asynchronous Programming
2. Asynchronous Programming
What are Promises?
- We previously mentioned that
callbackfunctions are used when working with asynchronous programming, however that’s not the only method - Promises are the more modern way to work with asynchronous code
- A
Promiseis an object which represents the eventual failure or completion of an asynchronous operation - It represents that eventual result with a few states:
- Pending: A penidng promise represents an asynchronous operation which is still ongoing, and doesn’t have a concrete result yet
- Fulfilled: The asynchronous operation has completed successfully, and a result is available
- Rejected: The asynchronous operation has failed, and an error is available
Creating a Promise
- The main way to create a
Promiseis with thePromiseconstructor - The constructor takes a function with two arguments:
resolve: This function should be called when thePromisesucceedsreject: This function should be called if thePromisefails
- Factory methods also exist to simplify this process, including:
Promise.resolvewhich takes a value as a parameter and returns a fulfilledPromisewith the provided value as the resultPromise.rejectwhich takes an error as a parameter and returns a rejectedPromisewith the provided error available
Using promises
- There are three main methods used to handle the result of a
Promisethey are:then(): Runs after a promise is fulfilled.thentakes one parameter, a callback function which is ran with the result of thePromiseas a parametercatch(): Runs if a promise is rejected.catchtakes one parameter, a callback function which is ran with the error that is thrown when thePromiseis rejectedfinally(): Runs last, after thethenorcatchoperation, and runs regardless of whether or not thePromiseis rejected or fulfilled.finallytakes a callback function as a parameter
- Each of these methods returns a new
Promiseupon which, the above methods can be used
Chaining Promises
As mentioned earlier, each call to
then,catchorfinallyreturns a newPromiseobjectThis allows you to chain Promises together
Example:
const myPromise = Promise.resolve("Hello"); myPromise .then((result) => { console.log(result); return "World"; }) .then((result) => { console.log(result); });- This would print:
Hello World
Async/Await
asyncandawaitare syntactic sugar built on top of Promises- They allow you to write
asynchronouscode that looks like synchronous code, so it can be easier to reason about - Examples of
async/await:- Assume we have the following function to fetch data:
function fetchData() { return new Promise((resolve, reject) => { const success = true; if (success) { resolve('Data fetched successfully'); } else { reject('Error fetching data'); } }); } - If we wanted to safely call it with the usual Promise syntax, we could write something like:
fetchData() .then((data) => console.log(data)); .catch((error) => console.error(error)); - That same code could be written like the following using
async/awaittry { const data = await fetchData(); console.log(data); } catch (error) { console.error(error); }
- Assume we have the following function to fetch data: