Skip to content

Instantly share code, notes, and snippets.

@jo32
Created August 16, 2019 07:53
Show Gist options
  • Save jo32/f29565201bd12c0fb46fe76b9fe4f91f to your computer and use it in GitHub Desktop.
Save jo32/f29565201bd12c0fb46fe76b9fe4f91f to your computer and use it in GitHub Desktop.
Promisify WeApp API in TypeScript and preserving type.
interface WxApiOpts<T, K>{
[k: string]: any,
success?: (callbackPayload: T) => any,
fail?: (callbackPayload: K) => any
}
/**
* 本方法将类似于 wx.request 等函数转化为 Promise 调用方式
* @param callbackStyleFunction 被转换的函数,该类型函数只接受一个 Object 类型参数,且必须具备 success 和 fail 回调。
* @param opts 防止 success 回调叫 success 的情况,传此参数进行重载。
*/
export default function <T, K>(callbackStyleFunction: (input?: WxApiOpts<T, K>) => any) {
return function (input?: WxApiOpts<T, K>): 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>;
let __opts = Object.assign({}, input, callbacks) as WxApiOpts<T, K>;
callbackStyleFunction(__opts)
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment