【问题标题】:Nested wrapper functions are returning Promise<Promise<T>>嵌套包装函数返回 Promise<Promise<T>>
【发布时间】:2020-12-12 08:42:40
【问题描述】:

我有一个包装函数 (doesPromiseyThings),它接受一个 thunk 并在 Promise 中返回 thunk 的返回值。我想创建另一个包装器来处理 thunk 的创建 - 创建一个函数,该函数采用与原始参数相同的参数,返回原始的 Promise 包装类型,并在执行时通过 doesPromiseyThings 传递函数。

当我尝试这样做时,传入一个返回承诺的函数,我返回的类型都是 Promise&lt;Promise&lt;T&gt;&gt;,TypeScript 抱怨这与 Promise&lt;T&gt; 不一样我试图分配返回值到。

async function foo(param: number) {
    return param;
}

function doesPromiseyThings<T>(fn: () => T): Promise<T> {
    return Promise.resolve(fn());
}

function wrapper<T,U>(fn: (...args: T[]) => U) {
    return (...args: T[]) => doesPromiseyThings(fn);
}

const wrappedFoo = wrapper(foo);
// (...args: number[]) => Promise<Promise<number>>

const output = wrappedFoo(1);
// Promise<Promise<number>>

我尝试在包装器的返回值中解包 Promise,但这样做会出现类型错误:

function wrapper<T,U>(fn: (...args: T[]) => U): (...args: T[]) => Promise<U extends Promise<infer V> ? V : U> {
    return (...args: T[]) => doesPromiseyThings(fn);
}
/*
Type '(...args: T[]) => Promise<U>' is not assignable to type '(...args: T[]) => Promise<U extends Promise<infer V> ? V : U>'.
  Type 'Promise<U>' is not assignable to type 'Promise<U extends Promise<infer V> ? V : U>'.
    Type 'U' is not assignable to type 'U extends Promise<infer V> ? V : U'.(2322)
*/

【问题讨论】:

    标签: typescript promise es6-promise


    【解决方案1】:

    我不确定你这样做是为了达到什么目的,但我能够让这段代码 sn-p 工作。

    另外,您在包装时也没有传递参数..

    另外,请尝试为这些事情寻找装饰器: https://www.typescriptlang.org/docs/handbook/decorators.html

    async function foo(param: number) {
        return param
    }
    
    function doesPromiseyThings<T>(fn: (args) => T, args): Promise<T> {
        const promise = new Promise<T>((resolve) => resolve(fn(args)))
        return promise
    }
    
    function wrapper<T, U>(fn: (args: T) => U) {
        return (args: T) => doesPromiseyThings(() => fn(args), args)
    }
    
    const wrappedFoo = wrapper(foo)
    
    const output = async () => {
        console.log(await wrappedFoo(1))
    }
    
    output()
    

    对于..args

    function foo(param: number) {
        return param
    }
    
    function doesPromiseyThings<T>({ fn }: { fn: (...args: T[]) => T }): Promise<T> {
        const promise = new Promise<T>((resolve) => resolve(fn()))
        return promise
    }
    
    function wrapper<T, U>(fn: (...args: T[]) => U) {
        return (...args: T[]) => doesPromiseyThings({ fn: () => fn(...args) })
    }
    
    const wrappedFoo = wrapper(foo)
    
    const output = async () => {
        console.log(await wrappedFoo(1))
    }
    
    output()
    

    【讨论】:

      猜你喜欢
      • 2019-01-09
      • 2020-06-12
      • 2019-12-19
      • 2014-02-21
      • 2021-06-05
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多