Created
November 26, 2020 13:36
-
-
Save rsgok/dfb7039a14d0fdf1aad5fd4662c412e8 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
// 闭包更加好嘛 | |
// 就是新手看不懂了 | |
const urls = { | |
getApp: '/api/app/get', | |
delApp: '/api/app/del' | |
} | |
const getAppList = reqWrapper((params) => request.get(urls.getApp, { params }), (res) => { | |
// ... | |
return newRes; | |
}); | |
const delApp = reqWrapper((data) => request.post(urls.delApp, data)); | |
function reqWrapper(reqFunc, resultTransformation) { | |
return async(data) => { | |
try { | |
const res = await reqFunc(data); | |
if (res.ResponseMetadata && !res.ResponseMetadata.Error) { | |
const result = res.Result; | |
if (resultTransformation) { | |
return resultTransformation(result); | |
} | |
return result; | |
} | |
emitLog(safeGet(res, 'ResponseMetadata.Error.Code'), 'error'); | |
return Promise.reject(res); | |
} catch (err) { | |
Promise.reject(err); | |
} | |
}; | |
} | |
const apis = { | |
getApp, | |
delApp, | |
}; | |
export async function callAppAPI(name, data) { | |
try { | |
return await apis[name](data); | |
} catch (err) { | |
return Promise.reject(err); | |
} | |
} |
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
// 原来的wrapper | |
const urls = { | |
getApp: '/api/app/get', | |
delApp: '/api/app/del' | |
} | |
const apis = { | |
getApp, | |
delApp | |
} | |
async function getApp(params) { | |
const res = await request.get(urls.getApp, { params }); | |
const successFunc = (oldRes) => { | |
// ... | |
return newRes | |
} | |
return reqWrapper(res, successFunc) | |
} | |
async function delApp(data) { | |
const res = await request.post(urls.delApp, data); | |
return reqWrapper(res); | |
} | |
async function reqWrapper(res, successFunc, failFunc) { | |
if (res.ResponseMetadata && !res.ResponseMetadata.Error) { | |
if (successFunc) { | |
return successFunc(res.Result); | |
} | |
return res.Result; | |
} | |
emitLog(safeGet(res, 'ResponseMetadata.Error.Code'), 'error'); | |
throw new Error(res); | |
} | |
export function callAppAPI(name, data) { | |
try { | |
return await apis[name](data); | |
} catch (err) { | |
return Promise.reject(err); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
中间还用过有点像反射的
(懒得改了,这是业务线上的一段逻辑)