簡體   English   中英

函數包裝器返回函數而不是實際對象

[英]Function wrapper returning function instead of actual object

我正在嘗試圍繞異步函數創建一個包裝器,當我調用該函數時,我總是得到一個函數而不是我想要得到的對象。

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 
})

我錯過了什么?
任何幫助將不勝感激。

您不是在調用該函數,而是將其包裝在括號中。 我相信這就是你所需要的。

 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 })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM