Home > Back-end >  Call async function in a normal function
Call async function in a normal function

Time:06-04

I have an async function (Which calls a Third Party API). I want to call inside normal function. How can I do it?

export const extractDetailsFromAPI = async (Adhaar: any): Promise<{ name: string; State: string; City: string }> =>
{
    const result = await thirdPartyService.SearchByAdhaar(Adhaar)
    const response = {
        name: Adhaar,
        State: result ? result.State : "",
        City: result ? result.City : ""
    };
    return response;
};

Above function is an Async function, I need to call it inside normal function without await. How can i do it? Also i am not getting response getting evaluated. Above thing is not working even with a callback. enter image description here

CodePudding user response:

You can put an async function inside of the function and return that, then handle the promise elsewhere. However, it's hard to tell if this will work for your use case without more information.

export const exampleFunction = () => {
    return (async () => {
        // Do whatever here, including any async functions
        return "SOME_VALUE";
    })();
}

// Then you can handle the promise with .then
exampleFunction()
    .then((value) => /* do something */);

// Or use await in an async function
export const someAsyncFunction = async () => {
    let value = await exampleFunction();
};

CodePudding user response:

There are a few ways to go about this.

Making the outer function async

If possible, you can make the outer function asynchronous. Whether this is practical entirely depends on context and it may require additional tweaking (sometimes resulting in a domino effect where you have to make very large portions of your code asynchronous). There may be libraries which make handling async/await easier depending on your situation, have a look around npm first.

.then()

In Javascript, async functions return Promises (which you've also defined as the return type of the function).

Objects which have a .then() function are called thenable. Promises, i.e. what's returned by an async function, have that method. This means you can execute code dependent on extractDetailsFromAPI once the function has returned a value, like so—

extractDetailsFromAPI("1234-5678-1234-5678").then(result => {
  // Do something with the result
  // For instance, send it in an HTTP response
  res.end(result);
})

Using an IIFE

An Immediately-Invoked Function Expression is a common pattern in Javascript, where you wrap your entire code in a function like this:

(function(){
  // Code goes here
})()

This allows you to make the function asynchronous and use await inside it:

(async function(){
  // ...
  data = await extractDetailsFromAPI("1234-5678-1234-5678");
})()
  • Related