Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to call a function that return another function in JavaScript ?
Next article icon

How to convert an asynchronous function to return a promise in JavaScript ?

Last Updated : 12 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to convert an asynchronous function to return a promise in JavaScript.

Approach:  You need to first declare a simple function (either a normal function or an arrow function (which is preferred)). You need to create an asynchronous function and then further you need to return the promise as an output from that asynchronous function.

We need to create a function (method), either a simple function or an arrow function (We are analyzing the facts using arrow functions). Create an asynchronous function and then upon calling that function we should return the output in the form of promise.

Let's first understand how to declare a simple arrow function in JavaScript and return the result associated with that function in the console.

Example:

JavaScript
<script>  let name = () =>{       console.log("GeeksforGeeks");   }   name(); </script> 

Output:

GeeksforGeeks

Approach:

  • We will add async() along with function syntax which will eventually handle all kinds of asynchronous operations and events.
  • After adding the async keyword, we will store the results.
  • After storing the results we will call the function and see that a promise is returned containing the state (as fulfilled) and value that was associated.

Example 1:

JavaScript
<script>   let name = async () => {     return "GeeksforGeeks";   };   console.log(name()); </script> 

Output:

Promise {<fulfilled>: "GeeksforGeeks"}  __proto__: Promise  [[PromiseState]]: "fulfilled"  [[PromiseResult]]: "GeeksforGeeks"

Example 2: You can also add await keyword and store that result in some variable. This is helpful when we fetch data from the API to wait for data to arrive properly.

JavaScript
<script>   let name = async () => {     let output = await ( "GeeksforGeeks");       return output;   };   console.log(name()); </script> 

Output:

Promise {<pending>: "GeeksforGeeks"}  __proto__: Promise  [[PromiseState]]: "fulfilled"  [[PromiseResult]]: "GeeksforGeeks"

Example 3: To have a look over the result we will use the then() method to print the result.

JavaScript
<script>   let name = async () => {     return "GeeksforGeeks";   };   name().then((value) => {     console.log(value);   }); </script> 

Output:

GeeksforGeeks

Approach 2: 

  • We will use resolve() state of the Promise.
  • We will store our result and then using both async keyword (along with function syntax) and await (before storing the result into a variable).

Example 1:

JavaScript
<script>   let name = async() =>{       let output = await Promise.resolve("GeeksforGeeks");       return output;   }   console.log(name()); </script> 

Output:

Promise {<pending>: "GeeksforGeeks"}  __proto__: Promise  [[PromiseState]]: "fulfilled"  [[PromiseResult]]: "GeeksforGeeks"

Example 2: If you wish to see the result also then as explained in the previous approach, you will use then() method, with the help of which you will see the result in the console.

JavaScript
<script> let name = async() =>{     let output = await Promise.resolve("GeeksforGeeks");     return output; } name().then((result)=>{     console.log(result); }); </script> 

Output:

GeeksforGeeks 

Next Article
How to call a function that return another function in JavaScript ?
author
amansingla
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Methods
  • JavaScript-Questions

Similar Reads

  • How To Return the Response From an Asynchronous Call in JavaScript?
    To return the response from an asynchronous call in JavaScript, it's important to understand how JavaScript handles asynchronous operations like fetching data, reading files, or executing time-based actions. JavaScript is a single-threaded nature means it can only handle one task at a time, but it u
    3 min read
  • How to create an Asynchronous function in Javascript?
    JavaScript is a single-threaded and synchronous language. The code is executed in order one at a time. But Javascript may appear to be asynchronous in some situations. Example: C/C++ Code <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" />
    6 min read
  • How to chain asynchronous functions in JavaScript ?
    JavaScript is a single-threaded, asynchronous programming language. Thus, some time-consuming operations like I/O, accessing the database, network calls, etc. are performed asynchronously so that it does not interrupt things in the only JS thread. This can be done by asynchronous code like promises
    3 min read
  • How to Convert Callback to Promise in JavaScript ?
    Asynchronous programming in JavaScript often involves the use of callbacks. However, callbacks can lead to callback hell and make the code harder to read and maintain. Promises provide a cleaner way to handle asynchronous operations. Converting existing callback-based code to use promises can improv
    2 min read
  • How to call a function that return another function in JavaScript ?
    The task is to call a function that returns another function with the help of JavaScript is called a Currying function, a function with numerous arguments that can be converted into a series of nesting functions with the help of the currying method. Approach:Define Outer Function:Create an outer fun
    2 min read
  • How to Store an Object sent by a Function in JavaScript ?
    When a function in JavaScript returns an object, there are several ways to store this returned object for later use. These objects can be stored in variables, array elements, or properties of other objects. Essentially, any data structure capable of holding values can store the returned object. Tabl
    2 min read
  • How to convert function call with two callbacks promise in Node.js ?
    Promise: Promise is used to handle the result, if it gets the required output then it executes the code of then block, and if it gets the error then it executes the code of the catch block. A promise looks like this - function() .then(data => { // After promise is fulfilled console.log(data); })
    3 min read
  • How a Function Returns an Object in JavaScript ?
    JavaScript Functions are versatile constructs that can return various values, including objects. Returning objects from functions is a common practice, especially when you want to encapsulate data and behavior into a single entity. In this article, we will see how a function returns an object in Jav
    3 min read
  • How to use await outside of an async function in JavaScript ?
    In this article, we will try to understand in what way or by how we may use await outside of an async function in JavaScript with the help of both theoretical explanations as well as coding examples. Let us first understand the following shown section in which all the syntaxes of declaring a promise
    4 min read
  • How to Return an Array from Async Function in Node.js ?
    Asynchronous programming in Node.js is fundamental for handling operations like network requests, file I/O, and database queries without blocking the main thread. One common requirement is to perform multiple asynchronous operations and return their results as an array. This article explores how to
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences