Use cases of async / await
Sraban Pahadasingh July 11, 2024 05:36 PMQ. What is the problem with the below snippets, assume srabanAsync() returns an api response.
let data;
async function sraban() {
try {
data = await srabanAsync();
} catch(err) {
console.log("Error", err);
}
}
sraban();
console.log("data", data);
Answer:
The main problem with the code is that console.log("data", data);
is executed before the sraban
function finishes its asynchronous operation. As a result, data
is likely to be undefined
at the time of logging. This happens because the sraban
function runs asynchronously, and JavaScript does not wait for it to complete before continuing with the next line of code.
Here's a breakdown of the issues:
- Asynchronous Execution: The
sraban
function is asynchronous and returns immediately after initiating theawait
operation. The logging statementconsole.log("data", data);
runs before the asynchronous operation completes. - Uninitialized Data: The
data
variable is uninitialized whenconsole.log
is called, so it logsundefined
.
To fix this, you can use one of the following approaches:
Using then
for chaining
You can call the sraban
function and chain a then
method to handle the logging once the data is available.
let data;
async function sraban() {
try {
data = await srabanAsync();
console.log("data", data); // Log data here after it is available
} catch(err) {
console.log("Error", err);
}
}
sraban(); // Call the function to start the async operation
Using an Immediately Invoked Function Expression (IIFE)
You can wrap the asynchronous code in an immediately invoked function expression (IIFE) to handle the async operation synchronously in a controlled block.
let data;
(async function() {
try {
data = await srabanAsync();
console.log("data", data); // Log data here after it is available
} catch(err) {
console.log("Error", err);
}
})();
Awaiting the Async Function Call
If you are in an async context (another async function), you can await the sraban
function call.
let data;
async function sraban() {
try {
data = await srabanAsync();
} catch(err) {
console.log("Error", err);
}
}
async function main() {
await sraban();
console.log("data", data); // Log data here after it is available
}
main(); // Call the main function to start the async operation
By ensuring the logging happens after the asynchronous operation completes, you can correctly capture and log the data
variable.