1

I have the following functions:

function f (x : number): number {
 return 1/x
}

function g (x : number): number {
 return x*x
}

function h (x : number): number {
 return f(g(x))
}

I am trying to convert h (g and f too if needed) to an asynchronous function just with callbacks and not with promises but I am stuck with that.

I know that each function should have a function callback as a parameter but I am not sure how to do that.

1
  • 1
    These are inherently synchronous functions; what you you mean by converting them to async? Commented May 30, 2019 at 16:21

1 Answer 1

3

We can start with f that provides an example of error management:

function f(x: number, cb: (err: any, result?: number) => void): void {
  if (x === 0)
    cb(new Error("Cannot call 'f' with zero"))
  else
    cb(null, 1/x)
}

Here is how to use it:

f(5, (err, result) => {
  if (!err)
    console.log("… do something with:", result)
})

The g function is easy:

function g(x: number, cb: (err: any, result?: number) => void): void {
    cb(null, x * x)
}

And h becomes to look like to a good old-fashioned callback hell:

function h(x: number, cb: (err: any, result?: number) => void): void {
    g(x, (err, gResult) => {
        if (err)
            cb(err)
        else
            f(gResult, cb)
    })
}

Thanks for this moment of nostalgia.

Sign up to request clarification or add additional context in comments.

2 Comments

There's nothing async about this though. It's just really awkward synchronous code :)
@JohnnyHK I assumed that the operations described in the question represented asynchronous stuff. We could write setTimeout but that's probably not what the author is looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.