gpt4 book ai didi

javascript - Typescript 通用方法装饰器返回 Promise 作为值

转载 作者:太空宇宙 更新时间:2023-11-04 03:00:11 24 4
gpt4 key购买 nike

我正在尝试实现一个通用方法装饰器,它可以与原型(prototype)方法和实例方法一起使用。

基于:Typescript decorators not working with arrow functions

从下面的代码中可以看到,instanceMethod() 返回了一个 Promise。

有什么方法可以返回正确的值吗?

装饰器代码:

export function trace(verbose: boolean = false) {

return (target: any, prop: string, descriptor?: TypedPropertyDescriptor<any>): any => {
let fn
let patchedFn

if (descriptor) {
fn = descriptor.value
}

return {
configurable: true,
enumerable: false,
get() {
if (!patchedFn) {
patchedFn = async (...args) => {
const ret = fn.call(this, ...args)
console.log(`typeof ret: ${typeof ret}`)
console.log(`return value: ${ret}`)
return ret
}
}
console.log(`get() patchedFn: ${patchedFn}`)
return patchedFn
},
set(newFn) {
console.log(`set() newFn: ${newFn}`)
patchedFn = undefined
fn = newFn
},
}

}
}

测试类和测试代码:

class Greeter {

@trace()
public instanceMethod(s: string): string {
return s
}

@trace()
public async instanceAsyncMethod(s: string): Promise<string> {
return s
}

@trace()
public instanceArrowMethod = (s: string): string => {
return s
}

}

async function test() {
const greeter = new Greeter()
const result1 = greeter.instanceMethod('1')
console.log(`* instanceMethod: ${result1}`) // should return '1', instead returns a Promise
const result2 = await greeter.instanceAsyncMethod('2')
console.log(`* instanceAsyncMethod: ${result2}`)
const result3 = await greeter.instanceArrowMethod('3')
console.log(`* instanceArrowMethod: ${result3}`)

}

test()

输出:

set() newFn: (s) => {
return s;
}
get() patchedFn: (...args) => __awaiter(this, void 0, void 0, function* () {
console.log(`typeof fn: ${typeof fn}`);
const ret = fn.call(this, ...args);
console.log(`typeof ret: ${typeof ret}`);
console.log(`return value: ${ret}`);
return ret;
})
typeof ret: string
return value: 1
* instanceMethod: [object Promise] <<<<<<<<<< The instance method is returning a Promise
get() patchedFn: (...args) => __awaiter(this, void 0, void 0, function* () {
console.log(`typeof fn: ${typeof fn}`);
const ret = fn.call(this, ...args);
console.log(`typeof ret: ${typeof ret}`);
console.log(`return value: ${ret}`);
return ret;
})
typeof ret: object
return value: [object Promise]
* instanceAsyncMethod: 2
get() patchedFn: (...args) => __awaiter(this, void 0, void 0, function* () {
console.log(`typeof fn: ${typeof fn}`);
const ret = fn.call(this, ...args);
console.log(`typeof ret: ${typeof ret}`);
console.log(`return value: ${ret}`);
return ret;
})
typeof ret: string
return value: 3
* instanceArrowMethod: 3

最佳答案

async 函数将始终返回一个 Promise。

您已将 patchedFn 定义为 async 函数,您必须进行修改以将其声明为普通函数,或者在调用方处 await(如果需要)。

关于javascript - Typescript 通用方法装饰器返回 Promise 作为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59674933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com