How to wait for a promise to finish before returning the variable of a function ? Last Updated : 18 Sep, 2024 Comments Improve Suggest changes Like Article Like Report Waiting for a promise to finish before returning a variable in a function is crucial when dealing with asynchronous operations in JavaScript, like fetching data from an API. Using async and await allows the function to pause execution until the promise resolves, ensuring reliable and expected results.To do that there are two popular ways described below.Table of ContentUse of setTimeout() functionUse of async or await() functionUse of setTimeout() functionUsing the setTimeout() function to wait for a promise involves delaying the execution of code by a specified time, allowing the promise to resolve before continuing. This method is less precise as it relies on estimated timing rather than directly handling the promise's resolution.Example: This example describes the setTimeout() method to wait for a promise to finish before returning the variable of a function. javascript // Returns a promise that resolves after `ms` milliseconds const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); // Logs failure message function failureCallback() { console.log("This is failure callback"); } // Waits 4 seconds, then logs and throws an error wait(4 * 1000).then(() => { console.log("waited for 4 seconds"); throw new Error("error occurred"); }).catch(() => { failureCallback(); // Handles the error }); // Waits 2 seconds, then logs message wait(2 * 1000).then(() => console.log("waited for 2 seconds")); Output:OutputUse of async or await() functionUsing async and await in JavaScript allows you to handle asynchronous operations more easily. The async keyword makes a function return a promise, while await pauses the function execution until the promise resolves, ensuring sequential and reliable code execution.Example: This example we demonstrates using async and await to handle asynchronous functions. It sequentially waits for two promises, each resolving after 2 and 4 seconds, then logs the results. javascript // This function returns promise after 2 seconds let first_function = function () { console.log("Entered first function"); return new Promise(resolve => { setTimeout(function () { resolve("\t\t This is first promise"); console.log("Returned first promise"); }, 2000); }); }; // This function executes returns promise after 4 seconds let second_function = function () { console.log("Entered second function"); return new Promise(resolve => { setTimeout(function () { resolve("\t\t This is second promise"); console.log("Returned second promise"); }, 4000); }); }; let async_function = async function () { console.log('async function called'); const first_promise = await first_function(); console.log("After awaiting for 2 seconds," + "the promise returned from first function is:"); console.log(first_promise); const second_promise = await second_function(); console.log("After awaiting for 4 seconds, the" + "promise returned from second function is:"); console.log(second_promise); } async_function(); Output:async function called Entered first function Returned first promise After awaiting for 2 seconds, the promise returned from first function is: This is first promise Entered second function Returned second promise After awaiting for 4 seconds, the promise returned from second function is: This is second promise Comment More infoAdvertise with us S sathiyajith19 Follow Improve Article Tags : Technical Scripter JavaScript Web Technologies javascript-functions JavaScript-Questions +1 More Similar Reads How to Encode and Decode a URL in JavaScript? Encoding and decoding URLs in JavaScript is essential for web development, especially when making GET requests with query parameters. This process ensures special characters in URLs are correctly interpreted by the server. For instance, spaces are converted to %20 or + in URLs. This guide covers how 4 min read How to declare the optional function parameters in JavaScript ? Declaring optional function parameters in JavaScript means defining function parameters that aren't required when the function is called. You can assign default values to these parameters using the = syntax, so if no argument is provided, the default value is used instead. These are the following ap 3 min read How to get the javascript function parameter names/values dynamically ? In this article, we are given any arbitrary JavaScript function and the task is to return the parameter names of the function. Approach: JavaScript contains a method called toString() which is used to represent a function code in its string representation. This method is used to get the parameter na 2 min read How To Include a JavaScript File in Another JavaScript File? The import and export syntax available in ES6 (ECMAScript 2015) module is used to include a JavaScript file in another JavaScript file. This approach is the most modern and recommended way to share code between JavaScript files.It allows you to break your code into smaller modules and then import th 4 min read How to override a JavaScript function ? In this article, we are given an HTML document and the task is to override the function, either a predefined function or a user-defined function using JavaScript. Approach: When we run the script then Fun() function is called. After clicking the button the GFG_Fun() function is called and this funct 2 min read Using the function* Declaration in JavaScript The function* declaration is used to define a generator that returns a Generator object. Generators are very powerful for asynchronous programming as they aim to resolve callback problems. In a generator, the yield keyword is used instead of return. The yield statement suspends the functionâs execut 2 min read What is the difference between call and apply in JavaScript ? JavaScript call() Method: It calls the method, taking the owner object as an argument. The keyword this refers to the 'owner' of the function or the object it belongs to. We can call a method that can be used on different objects. Syntax: object.objectMethod.call( objectInstance, arguments ) JavaScr 2 min read How to find out the caller function in JavaScript? In this article, we see the methods to find out the caller function in Javascript. Sometimes, the developer may want to modify how a function works on the basis of its caller function. To find out the caller function name, we will use the Function object's caller property. Property: Function.caller 1 min read How to negate a predicate function in JavaScript ? In this article, we will see how to negate a predicate function in JavaScript. Predicate functions are the ones that check the condition and return true and false based on the argument. Our task is to get the opposite of the predicate function. We follow the following method to get the desired resul 3 min read How to iterate over a callback n times in JavaScript? Given a callback function, we have to iterate over a callback n times. The callback is a function that is passed as an argument. To iterate over the callback function, we have to run the callback function n time.Here we have some common approaches:Table of ContentUsing recursion to iterate the n tim 4 min read Like