跳到主要内容
版本:3.x

Taro.interceptorify(promiseifyApi)

包裹 promiseify api 的洋葱圈模型

支持情况:

类型

<T, R>(promiseifyApi: promiseifyApi<T, R>) => Interceptorify<T, R>

参数

promiseifyApi

(requestParams: T) => Promise<R>
参数类型
requestParamsT

InterceptorifyChain

参数类型
requestParamsT
proceedpromiseifyApi<T, R>

InterceptorifyInterceptor

(chain: InterceptorifyChain<T, R>) => Promise<R>
参数类型
chainInterceptorifyChain<T, R>

Interceptorify

request

(requestParams: T) => Promise<R>
参数类型
requestParamsT

addInterceptor

(interceptor: InterceptorifyInterceptor<T, R>) => void
参数类型
interceptorInterceptorifyInterceptor<T, R>

cleanInterceptors

() => void

示例代码

示例 1

// 创建实例
const modalInterceptorify = interceptorify(taro.showModal)
// 添加拦截器
modalInterceptorify.addInterceptor(async function (chain) {
const res = await chain.proceed({
...chain.requestParams,
title: 'interceptor1'
})
return res
})
modalInterceptorify.addInterceptor(async function (chain) {
const res = await chain.proceed({
...chain.requestParams,
content: 'interceptor2'
})
return res
})
// 使用
modalInterceptorify.request({})

示例 2

// 创建实例
const fetchDataInterceptorify = interceptorify(taro.request)
// 添加拦截器
fetchDataInterceptorify.addInterceptor(async function (chain) {
taro.showLoading({
title: 'Loading...'
})
const res = await chain.proceed(chain.requestParams)
taro.hideLoading()
return res
})
fetchDataInterceptorify.addInterceptor(async function (chain) {
const params = chain.requestParams
const res = await chain.proceed({
url: 'http://httpbin.org' + params.url,
})
return res.data
})
// 使用
fetchDataInterceptorify.request({
url: '/ip'
}).then((res) => {
// log my ip
console.log(res.origin)
})