Ezert Aracksam
Ezert Aracksam

Reputation: 161

How to pass async function as parameter

I'm using a function that extracts data from a GitHub repository. It returns an object with metrics like the number of closed issues, etc. This function is passed as a parameter of another function that stores these metrics in a database.

store(extract());

The problem is that the extract function is asynchronous (and for some reason, it needs to be asynchronous) and is not returning values... I don't know how to manage async very well. How I force store() to wait for extract() return the metrics?

Thanks in advance.

Upvotes: 11

Views: 27285

Answers (4)

eddyP23
eddyP23

Reputation: 6825

I ended up here trying to find a solution to a similar problem, so for other unlucky lads like me, gonna paste what I figured out, the following works:

async function A(B: () => Promise<void>) {
    await B();
}

Now I want to call A and pass an async function, then I do it like this:

await A(async () => {
    await wait(3000);
})

Upvotes: 20

Guerric P
Guerric P

Reputation: 31805

Either use an async IIFE like this:

(async () => {
   const result = await extract();
   store(result);
})();

Or use the classic syntax:

extract().then(store);

Upvotes: 0

xdeepakv
xdeepakv

Reputation: 8125

Async function is nothing but a function return promise. take sample.

const getPromise = () =>  Promise.resolve("1")

const store = (fn) => {
  fn().then(console.log)
}
store(getPromise)

const storeCB = (fn, cb) => {
  fn().then(cb)
}
store(getPromise, console.log)

const storeThen = (fn) => {
  return fn().then(x => "append: " + x)
}
storeThen(getPromise).then(console.log)

const getAsync = async () =>  "2"

store(getAsync)


const storeWithAwait = async (fn) => {
  const restult = await fn()
  return restult
}

storeWithAwait(getAsync).then(console.log)

Upvotes: 1

Ilijanovic
Ilijanovic

Reputation: 14904

Did you try something like this?

(async ()=>{
   const result = await extract();
   store(result);
})()

Upvotes: 0

Related Questions