Created
November 20, 2019 08:09
-
-
Save jo32/0c976044372067a32a0f61f1275e0433 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface GWxApiOpts<T, K> { | |
success?: (callbackPayload: T) => any, | |
fail?: (callbackPayload: K) => any | |
} | |
type WxApiOpts<T, K, V> = { | |
[X in keyof V]: V[X] | |
} & GWxApiOpts<T, K> | |
/** | |
* 本方法将类似于 wx.request 等函数转化为 Promise 调用方式 | |
* @param callbackStyleFunction 被转换的函数,该类型函数只接受一个 Object 类型参数,且必须具备 success 和 fail 回调。 | |
* @param opts 防止 success 回调叫 success 的情况,传此参数进行重载。 | |
*/ | |
export default function <T, K, V>(callbackStyleFunction: (input?: WxApiOpts<T, K, V>) => any) { | |
return function (input?: WxApiOpts<T, K, V>): Promise<T> { | |
return new Promise((resolve: (val: T) => void, reject: (val: K) => void) => { | |
let callbacks = { | |
success: (res) => { | |
resolve(res); | |
}, | |
fail: (error) => { | |
reject(error); | |
} | |
}; | |
input = input || {} as WxApiOpts<T, K, V>; | |
let __opts = Object.assign({}, input, callbacks) as WxApiOpts<T, K, V>; | |
callbackStyleFunction(__opts) | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment