Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 943
Ezert Aracksam Avatar asked Mar 24 '26 21:03

Ezert Aracksam


2 Answers

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);
})
like image 74
eddyP23 Avatar answered Mar 27 '26 12:03

eddyP23


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)
like image 35
xdeepakv Avatar answered Mar 27 '26 10:03

xdeepakv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!