繁体   English   中英

转换柯里化形式 promise 链的问题

[英]Problem with converting currying form promise chain

我们有一个实用程序 function 包装axios http 调用; 目前它以链式 promise 的柯里化形式编写,如下所示:

request<T>(request: AxiosRequestConfig, x: number, y: string, z: boolean): Promise<T> {
    return someFunction1(x)
             .then(someFunction2(y))
             .then(sendRequest(z))
             .catch((err) => { // handle error });
}
  function someFunction1(x: number): Promise<string> { }
  function someFunction2(y: string): (s: string) => Promise<AxiosRequestConfig> {}
  function sendRequest(z: boolean): (req: AxiosRequestConfig) => Promise<T> {
     // to other things...
     return axios.request<T>(req)
                 .then(processResponse);
  } 
  function processResponse(): (res: AxiosResponse<T>) => T { 
    // do other things...
    // do something with the res.
  }

要使用它,只需调用await request(someReq, 1, 'hello', false) 这可行,但现在我想将其转换为异步/等待形式,因为我想在sendRequest function 上注入一个包装器以添加额外的逻辑。 我试图将它们转换如下:

 // this now returns a normal promise instead of a function.
 function sendRequest<T>(z: boolean, req: AxiosRequestCofig): Promise<T> {
     // to other things...
     return axios.request<T>(req)
                 .then(processResponse);
 }

 // a function type
 type RealRequestCall<T> = (z: boolean, req: AxiosRequestConfig) => Promise<T>;

 // the wrapper
 async function requestWrapper(z: boolean, req: AxiosRequestConfig, realRequest: RealRequestCall<T>): Promise<T> {

    if (!z) {
      // this is when just forwards the request to the real request call.
      return realRequest(z, req).then(res => res);
    } else {
      const realResponse = await realRequestCall(z, req);
      // do something with the response
     return Promise.resolve(realResponse);
    }
  
 }

 // new request function now uses requestWrapper
function request<T>(request: AxiosRequestConfig, x: number, y: string, z: boolean): Promise<T> {
   return someFunction1(x)
                 .then(someFunction2(y))
                 .then(req => requestWrapper(z, req, sendRequest),
                       (err) => { // handle error });
}

但这不起作用; 我收到两个 axios 错误:

  1. 发送给客户端后无法设置 header
  2. 类型错误:无法在 sendRequest (/dist/util/http.util.js:102:24) 处读取未定义的属性“processResponse”\n 在 Object。 (/dist/util/configProxy.js:20:20)

我在转换过程中做错了什么?

看起来您包装sendRequest的方法不起作用,因为 function 包括完整的请求响应周期(它在返回之前等待响应)。

你有几个选择:

  1. 在调用它的地方完全替换sendRequest ,而不是包装。
  2. 更改sendRequest的接口,使其不等待 url 调用解决。
  3. 使用 axios拦截器

3 可能是你最好的选择,因为它是侵入性最小的,尽管它有一些“神奇”的缺点。 如果客户端代码高度本地化或任务预计更大,我更喜欢 1 或 2。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM