0

I'm trying to create a wrapper around an async function, when I call the function I always get a function instead of the object I want to get.

function wrap<T extends Function>(fn: T){
    return <any> async function (...args) {
        let result = await fn(...args)
        return {
            statusCode: 200,
            body: JSON.stringify({
                data: result

            }),
        }
    };
}

let main = async (test: string) => {
    console.log(`calling api  ${test}`);
    return wrap(() => {
        console.log("")
        return {
            foo: "bar",
        }
    });
};

main("test").then((res)=>{
    console.log(res)
    console.log(typeof res)  // <-- function 
})

What I'm missing ?
Any help will be appreciated.

Ben Rhouma Zied
  • 2,473
  • 3
  • 19
  • 29
  • 1
    But you are returning a function `return async function (...args) { let result = await fn(...args) return { statusCode: 200, body: JSON.stringify({ data: result }), } };` – pilchard Sep 11 '20 at 21:50

1 Answers1

1

You are not invoking the function, you are just wrapping it in parenthesis. I believe this is what you need.

function wrap<T extends Function>(fn: T){
    return <any> async function (...args) {
        let result = await fn(...args)
        return {
            statusCode: 200,
            body: JSON.stringify({
                data: result

            }),
        }
    };
}

let main = async (test: any) => {
    console.log(`calling api  ${test}`);
    return wrap(() => {
        console.log("")
        return {
            foo: "bar",
        }
    })();
};

main("test").then((res)=>{
    console.log(res)
    console.log(typeof res)  // <-- object
})
Ronald M. Kasendwa
  • 410
  • 1
  • 4
  • 11