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( "neveropen" ); } name(); </script> |
Output:
neveropen
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 "neveropen" ; }; console.log(name()); </script> |
Output:
Promise {<fulfilled>: "neveropen"} __proto__: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: "neveropen"
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 ( "neveropen" ); return output; }; console.log(name()); </script> |
Output:
Promise {<pending>: "neveropen"} __proto__: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: "neveropen"
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 "neveropen" ; }; name().then((value) => { console.log(value); }); </script> |
Output:
neveropen
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( "neveropen" ); return output; } console.log(name()); </script> |
Output:
Promise {<pending>: "neveropen"} __proto__: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: "neveropen"
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( "neveropen" ); return output; } name().then((result)=>{ console.log(result); }); </script> |
Output:
neveropen