Callback and Promise in
JavaScript
By: Faheem Uz Zaman & Alifya Hussain
Callbacks, Promises, and Async
+ Synchronous operations in JavaScript entails having each step of an operation waits for the previous
step to execute completely. This means no matter how long a previous process takes, subsquent process
won't kick off until the former is completed. Asynchronous operations, on the other hand, defers
operations. Any process that takes a lot of time to process is usually run alongside other synchronous
operation and completes in the future.
+ This lesson dwells on fundamental concepts that JavaScript relies on to handle asynchronous
operations. These concepts include: Callback functions, Promises and the use of Async and Await to
handle deferred operations in JavaScript.
Asynchronous Operations
Operations in JavaScript are traditionally synchronous and execute from top to bottom. For instance, a
farming operation that logs farming process to the console:
Asynchronous Operations
Operations in JavaScript are traditionally synchronous and execute from top to bottom. For instance, a
farming operation that logs farming process to the console:
Functions are First-Class Objects
+ It's important to keep in mind before going
through the rest of these lessons that JavaScript
Functions are first-class objects in and as such
can functions have the ability to:
• Be assigned to variables (and treated as a value)
• Have other functions in them
• Return other functions to be called later
Callback Functions
+ When a function simply accepts another function
as an argument, this contained function is known
as a callback function. Using callback functions is a
core functional programming concept, and you can
find them in most JavaScript code; either in simple
functions like setInterval, event listening or when
making API calls.
Callback Functions
Naming Callback functions
+ Callback functions can be named or anonymous functions. In our first
examples, we used anonymous callback functions. Let’s look at a
named callback function:
Naming Callback functions
function introduction(firstName, lastName, callback)
{
const fullName = `${firstName} ${lastName}`;
callback(fullName);
}
introduction('Chris','Nwamba', greeting);
Promises
+ I promise to do this whenever that is true. If it isn't true, then I won't.
+ This is a simple illustration of JavaScript Promises. Sounds like an IF statement? We’ll soon see a huge difference.
+ A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an
asynchronous block of code to completely execute before other synchronous parts of the code can run. For instance,
when making API requests to servers, we have no idea if these servers are offline or online, or how long it takes to
process the server request.
+ With Promises, we can defer execution of a code block until an async request is completed. This way, other
operations can keep running without interruption.
+ Promises have three states:
• Pending: This is the initial state of the Promise before an operation begins
• Fulfilled: This means the specified operation was completed
• Rejected: The operation did not complete; an error value is usually thrown
Creating a Promise
Creating a Promise
const weather = true
const date = new Promise(function(resolve, reject) {
if (weather)
{
const dateDetails = {
name: 'Cubana Restaurant’,
location: '55th Street’,
table: 5 };
resolve(dateDetails)
} else {
reject(new Error('Bad weather, so no Date')) } }
);
Using Promises
+ Using a promise that has been created is relatively
straightforward; we chain .then() and .catch() to our Promise like
so:
Using Promises
+ Using a promise that has been created is
relatively straightforward; we chain .then()
and .catch() to our Promise like so:
Await
+ Await is only used with an async function. The await keyword is
used in an async function to ensure that all promises returned in
the async function are synchronized, i:e. they wait for each
other. Await eliminates the use of callbacks in .then() and
.catch(). In using async and await, async is prepended when
returning a promise, await is prepended when calling a promise.
try and catch are also used to get the rejection value of an async
function. Let's see this with our date example:
Await
Await
Conclusion
+ Understanding the concepts of Callbacks, Promises, and Async/Await
can be rather confusing, but so far we have seen how they work when
carrying out asynchronous operations in JavaScript.