gpt4 book ai didi

javascript - 如何使用 Reflect.getMetadata 检查 Async/Promise

转载 作者:行者123 更新时间:2023-12-05 06:47:27 24 4
gpt4 key购买 nike

我在测试时发现了这个错误 https://github.com/ztytotoro/rxjs-extension/blob/master/src/decorators.ts#L20

export const AsyncFunction = async function () {}.constructor;

export function isAsyncOrPromise(fn: any): boolean {
return fn instanceof Promise || fn instanceof AsyncFunction;
}

⏯ Playground 链接

Playground 链接: Provided

💻代码

function Log(target: any, key: string | symbol, descriptor: PropertyDescriptor): void {
const type = Reflect.getMetadata('design:returntype', target, key);
console.log(key, type.constructor.name);
}

class Demo {
@Log
async save(n: number): Promise<string> {
const result = await Promise.resolve(`${n} succeed`);
return result;
}
}
const demo = new Demo();

async function main(): Promise<any> {
console.log('main', main.constructor.name);
const result = await demo.save(1);
}

main();

🙁 实际行为

save Function
main AsyncFunction

🙂预期行为

save AsyncFunction
main AsyncFunction

演示2

function Log(target: any, key: string | symbol, descriptor: PropertyDescriptor): void {
const type = Reflect.getMetadata('design:returntype', target, key);
console.log(key, type instanceof Promise);
}

class Demo {
@Log
async save(n: number): Promise<string> {
const result = await Promise.resolve(`${n} succeed`);
return result;
}
}
const demo = new Demo();

async function main(): Promise<any> {
const result = await demo.save(1);
}

main();

Playground 链接: Provided

🙁 实际行为

save false

🙂预期行为

save true

最佳答案

很难找到解决方法 - 我无法解释它为什么有效

对于演示 1,我认为这是正确的实现:

function Log(target: any, key: string | symbol, descriptor: PropertyDescriptor): void {
const type = Reflect.getMetadata('design:returntype', target, key);
console.log(key, type.name); // 'Promise'
}

class Demo {
@Log
async save(n: number): Promise<string> {
const result = await Promise.resolve(`${n} succeed`);
return result;
}
}
const demo = new Demo();

async function main(): Promise<any> {
console.log('main', main.constructor.name); // 'AsyncFunction'
const result = await demo.save(1);
}

main();

演示2代码

function Log(target: any, key: string | symbol, descriptor: PropertyDescriptor): void {
const type = Reflect.getMetadata('design:returntype', target, key);
console.log(key, type === Promise); // true
}

class Demo {
@Log
async save(n: number): Promise<string> {
const result = await Promise.resolve(`${n} succeed`);
return result;
}
}
const demo = new Demo();

async function main(): Promise<any> {
const result = await demo.save(1);
}

main();

关于javascript - 如何使用 Reflect.getMetadata 检查 Async/Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67121015/

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