Open In App

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

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:




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

Output:

GeeksforGeeks

Approach:

Example 1:




<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.




<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.




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

Output:

GeeksforGeeks

Approach 2: 

Example 1:




<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.




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

Output:

GeeksforGeeks 

Article Tags :