重构小程序前端校验接口返参处理

原本代码是通过嵌套回调,控制提示之间的前后依赖关系,形成了回调地狱,需要重构。

主要是用 Map (ES6+) 处理 if (code){} else if (code){}​,并且利用 Promise 封装函数,配合 asyncawait (ES7+),使得异步操作同步化,抽离出嵌套的逻辑。后续代码维护只需要区分「仅提示」和「打断」两种模式,不需要考虑提示之间的互相依赖,后期维护成本大大降低。

比较业务代码可以发现,代码量直接干掉了 2/3。

原始代码

// util.js
/*
    封装wx.request请求
    url 接口url
    params 请求参数
    md 请求方式
    load 是否显示loading等待框
  */
const getResult = function (url, params, md, cb, load, ctype) {
  //封装wx,request请求
  var that = this;

  if (load) {
    wx.showLoading({
      mask: true,
      title: "拼命加载中",
    });
  }
  var requestParams = {
    url: ycConfig[ycConfig.env].domain_url + url,
    data: params,
    dataType: "json",
    method: md ? md : "POST",
    header: {
      "content-type": ctype || "application/json",
    },
    success: function (res) {
      wx.hideLoading();
      if (res.data && res.data.status == "error") {
        typeof cb == "function" && cb(res.data);
      } else {
        typeof cb == "function" && cb(res.data);
      }
    },
    complete: function (res) {},
    fail: function () {
      wx.hideLoading();
      wx.showToast({
        title: "网络连接异常",
        icon: "none",
      });
    },
  };
  wx.request(requestParams);
};

module.exports = {
  getResult,
};
// app.js
let { getResult } = require("utils/util.js");

App({
  getResult(url, params, md, cb, load, ctype) {
    var that = this;

    if (url != "/ffpLogin.pl") {
      var userInfo = wx.getStorageSync("globalUserInfo");

      //判断是否有效
      if (
        isEmpty(userInfo.wechatLoginToken) ||
        isEmpty(userInfo.wechatOpenId)
      ) {
        wx.clearStorage(); //清理登录缓存数据
        wx.showToast({
          title: "登录失效,请重新登录!",
          icon: "none",
        });

        wx.reLaunch({
          url: "/pages/login/login",
        });
        return;
      }
      params.wechatLoginToken = userInfo.wechatLoginToken;
      params.wechatOpenId = userInfo.wechatOpenId;
    }

    var dic = {};
    dic.cipher = that.encryption(params);

    function temp_cb(data) {
      if (data.code == "8888") {
        wx.clearStorage(); //清理登录缓存数据
        wx.showToast({
          title: "登录失效,请重新登录!",
          icon: "none",
        });

        wx.reLaunch({
          url: "/pages/login/login",
        });
        return;
      }
      typeof cb == "function" && cb(data);
    }
    getResult(url, dic, md, temp_cb, load, ctype);
  },
});
Page({
  //提交订单
  formSubmit: function (formSubmitRes) {
    var paraDic = {
      regPhone: this.data.regPhone,
      shipName: this.data.shipName,
      customer: this.data.customerName,
      planType: this.data.planCateID,
      customerType: this.data.customerID,
      arriveTime: this.data.isAllMention ? this.data.arrivalTime : "",
      takeSite: this.data.isTakeSite ? this.data.takeSiteID : "",
    };

    var that = this;

    //提交订单
    app.getResult(
      "/oilPlan/checkInfo.pl",
      paraDic,
      "POST",
      function (res) {
        var appleDetailDic = {};

        if (that.data.isTakeSite) {
          appleDetailDic = {
            regPhone: that.data.regPhone,
            planType: that.data.planCateID,
            customerType: that.data.customerID,
            siteId: that.data.saleSiteID,
            shipName: that.data.shipName,
            customer: formSubmitRes.detail.value.customerName,
            takeSite: that.data.takeSiteID,
            planCode: that.data.planCode,
            pagesType: "0", //type 0 新增,1 修改
            isAgain: "1", //修改识别
            shipLength: formSubmitRes.detail.value.shipLength, //船舶
            shipType: that.data.shipTypeSelect, //船舶类型
            shipLoad: that.data.shipLoadSelect, //载重
            isAllMention: that.data.isAllMention,
            nineyards: formSubmitRes.detail.value.nineyards, //九位码
            arrivalTime: that.data.arrivalTime, //预计到站时间
            otherPhone: formSubmitRes.detail.value.otherPhone,
          };
        } else {
          appleDetailDic = {
            regPhone: that.data.regPhone,
            planType: that.data.planCateID,
            customerType: that.data.customerID,
            siteId: that.data.saleSiteID,
            shipName: that.data.shipName,
            customer: formSubmitRes.detail.value.customerName,
            takeSite: "",
            planCode: that.data.planCode,
            pagesType: "0", //type 0 新增,1 修改
            isAgain: "1", //修改识别
            shipLength: formSubmitRes.detail.value.shipLength, //船舶
            shipType: that.data.shipTypeSelect, //船舶类型
            shipLoad: that.data.shipLoadSelect, //载重
            isAllMention: that.data.isAllMention,
            nineyards: formSubmitRes.detail.value.nineyards, //九位码
            arrivalTime: that.data.arrivalTime, //预计到站时间
            otherPhone: formSubmitRes.detail.value.otherPhone,
          };
        }

        if (res.code == "0000") {
          //判断是否修改
          if (that.data.isDataChange) {
            //修改
            wx.navigateTo({
              url:
                "/pages/plan/applyDetail/applyDetail?appleDetailDic=" +
                JSON.stringify(appleDetailDic),
            });
          } else {
            //再来一单的申请详情页
            wx.navigateTo({
              url:
                "/pages/plan/planAgain-detail/planAgain-detail?appleDetailDic=" +
                JSON.stringify(appleDetailDic),
            });
          }
        } else if (res.code == "0003") {
          wx.showModal({
            title: "提示",
            content: res.msg,
            success(res) {
              if (res.confirm) {
                //创建新船
                app.getResult(
                  "/oilPlan/addShip.pl",
                  paraDic,
                  "POST",
                  function (res) {
                    if (res.code == "0000") {
                      if (appleDetailDic.customerType != 3) {
                        app.getResult(
                          "/oilPlan/checkInfo.pl",
                          paraDic,
                          "POST",
                          function (res) {
                            if (res.code == "0000") {
                              //判断是否修改
                              if (that.data.isDataChange) {
                                //修改
                                wx.navigateTo({
                                  url:
                                    "/pages/plan/applyDetail/applyDetail?appleDetailDic=" +
                                    JSON.stringify(appleDetailDic),
                                });
                              } else {
                                //再来一单的申请详情页
                                wx.navigateTo({
                                  url:
                                    "/pages/plan/planAgain-detail/planAgain-detail?appleDetailDic=" +
                                    JSON.stringify(appleDetailDic),
                                });
                              }
                            } else if (res.code == "0010") {
                              //点击弹框
                              wx.showModal({
                                title: "提示",
                                content: res.msg,
                                confirmText: "确定",
                                cancelText: "取消",
                                success(res) {
                                  if (res.confirm) {
                                    //判断是否修改
                                    debugger;
                                    if (that.data.isDataChange) {
                                      //修改
                                      wx.navigateTo({
                                        url:
                                          "/pages/plan/applyDetail/applyDetail?appleDetailDic=" +
                                          JSON.stringify(appleDetailDic),
                                      });
                                    } else {
                                      //再来一单的申请详情页
                                      wx.navigateTo({
                                        url:
                                          "/pages/plan/planAgain-detail/planAgain-detail?appleDetailDic=" +
                                          JSON.stringify(appleDetailDic),
                                      });
                                    }
                                  } else if (res.cancel) {
                                  }
                                },
                              });
                            } else {
                              wx.showToast({
                                title: res.msg,
                                icon: "none",
                              });
                            }
                          },
                          "ture"
                        );
                      } else {
                        if (that.data.isDataChange) {
                          //修改
                          wx.navigateTo({
                            url:
                              "/pages/plan/applyDetail/applyDetail?appleDetailDic=" +
                              JSON.stringify(appleDetailDic),
                          });
                        } else {
                          //再来一单的申请详情页
                          wx.navigateTo({
                            url:
                              "/pages/plan/planAgain-detail/planAgain-detail?appleDetailDic=" +
                              JSON.stringify(appleDetailDic),
                          });
                        }
                      }
                    } else {
                      wx.showToast({
                        title: res.msg,
                        icon: "none",
                      });
                    }
                  },
                  "ture"
                );
              } else if (res.cancel) {
              }
            },
          });
        } else if (res.code == "0008") {
          //点击弹框
          wx.showModal({
            title: "提示",
            content: res.msg,
            confirmText: "仍然选择",
            cancelText: "重新选择",
            success(res) {
              if (res.confirm) {
                paraDic.ignore = 1;
                app.getResult(
                  "/oilPlan/checkInfo.pl",
                  paraDic,
                  "POST",
                  function (res) {
                    if (res.code == "0000") {
                      if (that.data.isDataChange) {
                        //修改
                        wx.navigateTo({
                          url:
                            "/pages/plan/applyDetail/applyDetail?appleDetailDic=" +
                            JSON.stringify(appleDetailDic),
                        });
                      } else {
                        //再来一单的申请详情页
                        wx.navigateTo({
                          url:
                            "/pages/plan/planAgain-detail/planAgain-detail?appleDetailDic=" +
                            JSON.stringify(appleDetailDic),
                        });
                      }
                    } else if (res.code == "0010") {
                      //点击弹框
                      wx.showModal({
                        title: "提示",
                        content: res.msg,
                        confirmText: "确定",
                        cancelText: "取消",
                        success(res) {
                          if (res.confirm) {
                            //判断是否修改
                            if (that.data.isDataChange) {
                              //修改
                              wx.navigateTo({
                                url:
                                  "/pages/plan/applyDetail/applyDetail?appleDetailDic=" +
                                  JSON.stringify(appleDetailDic),
                              });
                            } else {
                              //再来一单的申请详情页
                              wx.navigateTo({
                                url:
                                  "/pages/plan/planAgain-detail/planAgain-detail?appleDetailDic=" +
                                  JSON.stringify(appleDetailDic),
                              });
                            }
                          } else if (res.cancel) {
                          }
                        },
                      });
                    } else if (res.code == "0003") {
                      wx.showModal({
                        title: "提示",
                        content: res.msg,
                        success(res) {
                          if (res.confirm) {
                            var paraDic = {
                              shipName: that.data.shipName,
                              customer: that.data.customerName,
                              customerType: that.data.customerID,
                            };
                            //创建新船
                            app.getResult(
                              "/oilPlan/addShip.pl",
                              paraDic,
                              "POST",
                              function (res) {
                                if (res.code == "0000") {
                                  if (appleDetailDic.customerType != 3) {
                                    var paraDic = {
                                      regPhone: appleDetailDic.regPhone,
                                      shipName: appleDetailDic.shipName,
                                      customer: appleDetailDic.customer,
                                      planType: appleDetailDic.planType,
                                      customerType: appleDetailDic.customerType,
                                      arriveTime: appleDetailDic.arriveTime,
                                      takeSite: appleDetailDic.takeSite,
                                    };

                                    app.getResult(
                                      "/oilPlan/checkInfo.pl",
                                      paraDic,
                                      "POST",
                                      function (res) {
                                        if (res.code == "0000") {
                                          //判断是否修改
                                          if (that.data.isDataChange) {
                                            //修改
                                            wx.navigateTo({
                                              url:
                                                "/pages/plan/applyDetail/applyDetail?appleDetailDic=" +
                                                JSON.stringify(appleDetailDic),
                                            });
                                          } else {
                                            //再来一单的申请详情页
                                            wx.navigateTo({
                                              url:
                                                "/pages/plan/planAgain-detail/planAgain-detail?appleDetailDic=" +
                                                JSON.stringify(appleDetailDic),
                                            });
                                          }
                                        } else if (res.code == "0010") {
                                          //点击弹框
                                          wx.showModal({
                                            title: "提示",
                                            content: res.msg,
                                            confirmText: "确定",
                                            cancelText: "取消",
                                            success(res) {
                                              if (res.confirm) {
                                                //判断是否修改
                                                debugger;
                                                if (that.data.isDataChange) {
                                                  //修改
                                                  wx.navigateTo({
                                                    url:
                                                      "/pages/plan/applyDetail/applyDetail?appleDetailDic=" +
                                                      JSON.stringify(
                                                        appleDetailDic
                                                      ),
                                                  });
                                                } else {
                                                  //再来一单的申请详情页
                                                  wx.navigateTo({
                                                    url:
                                                      "/pages/plan/planAgain-detail/planAgain-detail?appleDetailDic=" +
                                                      JSON.stringify(
                                                        appleDetailDic
                                                      ),
                                                  });
                                                }
                                              } else if (res.cancel) {
                                              }
                                            },
                                          });
                                        } else {
                                          wx.showToast({
                                            title: res.msg,
                                            icon: "none",
                                          });
                                        }
                                      },
                                      "ture"
                                    );
                                  } else {
                                    if (that.data.isDataChange) {
                                      //修改
                                      wx.navigateTo({
                                        url:
                                          "/pages/plan/applyDetail/applyDetail?appleDetailDic=" +
                                          JSON.stringify(appleDetailDic),
                                      });
                                    } else {
                                      //再来一单的申请详情页
                                      wx.navigateTo({
                                        url:
                                          "/pages/plan/planAgain-detail/planAgain-detail?appleDetailDic=" +
                                          JSON.stringify(appleDetailDic),
                                      });
                                    }
                                  }
                                } else {
                                  wx.showToast({
                                    title: res.msg,
                                    icon: "none",
                                  });
                                }
                              },
                              "ture"
                            );
                          } else if (res.cancel) {
                          }
                        },
                      });
                    } else {
                      wx.showToast({
                        title: res.msg,
                        icon: "none",
                      });
                    }
                  },
                  "ture"
                );
              } else if (res.cancel) {
              }
            },
          });
        } else if (res.code == "0010") {
          //点击弹框
          wx.showModal({
            title: "提示",
            content: res.msg,
            confirmText: "确定",
            cancelText: "取消",
            success(res) {
              if (res.confirm) {
                //判断是否修改
                debugger;
                if (that.data.isDataChange) {
                  //修改
                  wx.navigateTo({
                    url:
                      "/pages/plan/applyDetail/applyDetail?appleDetailDic=" +
                      JSON.stringify(appleDetailDic),
                  });
                } else {
                  //再来一单的申请详情页
                  wx.navigateTo({
                    url:
                      "/pages/plan/planAgain-detail/planAgain-detail?appleDetailDic=" +
                      JSON.stringify(appleDetailDic),
                  });
                }
              } else if (res.cancel) {
              }
            },
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      },
      "ture"
    );
  },
});

重构后的代码

// util.js
// 封装 wx.request() 返回 Promise
const wxRequest = (url, params, md, load, ctype) => {
  if (load) {
    wx.showLoading({
      mask: true,
      title: "拼命加载中",
    });
  }
  let taskController;
  let task = new Promise((resolve, reject) => {
    taskController = wx.request({
      url: ycConfig[ycConfig.env].domain_url + url,
      data: params,
      dataType: "json",
      method: md ? md : "POST",
      header: {
        "content-type": ctype || "application/json",
      },
      success: (res) => {
        wx.hideLoading();
        resolve(res);
      },
      fail: (err) => {
        reject(() => {
          wx.hideLoading();
          wx.showToast({
            title: "网络连接异常",
            icon: "none",
          });
        });
      },
    });
  });
  return { task, taskController };
};

module.exports = {
  wxRequest,
};
// app.js
let { wxRequest } = require("utils/util.js");

App({
  getRequest(url, params, md, load, ctype) {
    var that = this;

    if (url != "/ffpLogin.pl") {
      var userInfo = wx.getStorageSync("globalUserInfo");

      //判断是否有效
      if (
        isEmpty(userInfo.wechatLoginToken) ||
        isEmpty(userInfo.wechatOpenId)
      ) {
        wx.clearStorage(); //清理登录缓存数据
        wx.showToast({
          title: "登录失效,请重新登录!",
          icon: "none",
        });

        wx.reLaunch({
          url: "/pages/login/login",
        });
        return;
      }
      params.wechatLoginToken = userInfo.wechatLoginToken;
      params.wechatOpenId = userInfo.wechatOpenId;
    }

    var dic = {};
    dic.cipher = that.encryption(params);
    return new Promise((resolve, reject) => {
      wxRequest(url, dic, md, load, ctype).task.then((res) => {
        if (res.code == "8888") {
          wx.clearStorage(); //清理登录缓存数据
          wx.showToast({
            title: "登录失效,请重新登录!",
            icon: "none",
          });

          wx.reLaunch({
            url: "/pages/login/login",
          });
          return;
        } else {
          resolve(res);
        }
      });
    });
  },
});
// 业务代码
Page({
  checkInfo: (paraDic) => {
    return app.getRequest("/oilPlan/checkInfo.pl", paraDic, "POST", "ture");
  },
  addShip: (paraDic) => {
    return app.getRequest("/oilPlan/addShip.pl", paraDic, "POST", "ture");
  },
  innerRouter: function (isDataChange, appleDetailDic) {
    if (isDataChange) {
      //修改
      wx.navigateTo({
        url:
          "/pages/plan/applyDetail/applyDetail?appleDetailDic=" +
          JSON.stringify(appleDetailDic),
      });
    } else {
      //再来一单的申请详情页
      wx.navigateTo({
        url:
          "/pages/plan/planAgain-detail/planAgain-detail?appleDetailDic=" +
          JSON.stringify(appleDetailDic),
      });
    }
  },
  //提交订单
  formSubmit: function (formSubmitRes) {
    var paraDic = {
      regPhone: this.data.regPhone,
      shipName: this.data.shipName,
      customer: this.data.customerName,
      planType: this.data.planCateID,
      customerType: this.data.customerID,
      arriveTime: this.data.isAllMention ? this.data.arrivalTime : "",
      takeSite: this.data.isTakeSite ? this.data.takeSiteID : "",
    };

    var that = this;
    var appleDetailDic = {};

    if (that.data.isTakeSite) {
      appleDetailDic = {
        regPhone: that.data.regPhone,
        planType: that.data.planCateID,
        customerType: that.data.customerID,
        siteId: that.data.saleSiteID,
        shipName: that.data.shipName,
        customer: formSubmitRes.detail.value.customerName,
        takeSite: that.data.takeSiteID,
        planCode: that.data.planCode,
        pagesType: "0", //type 0 新增,1 修改
        isAgain: "1", //修改识别
        shipLength: formSubmitRes.detail.value.shipLength, //船舶
        shipType: that.data.shipTypeSelect, //船舶类型
        shipLoad: that.data.shipLoadSelect, //载重
        isAllMention: that.data.isAllMention,
        nineyards: formSubmitRes.detail.value.nineyards, //九位码
        arrivalTime: that.data.arrivalTime, //预计到站时间
        otherPhone: formSubmitRes.detail.value.otherPhone,
      };
    } else {
      appleDetailDic = {
        regPhone: that.data.regPhone,
        planType: that.data.planCateID,
        customerType: that.data.customerID,
        siteId: that.data.saleSiteID,
        shipName: that.data.shipName,
        customer: formSubmitRes.detail.value.customerName,
        takeSite: "",
        planCode: that.data.planCode,
        pagesType: "0", //type 0 新增,1 修改
        isAgain: "1", //修改识别
        shipLength: formSubmitRes.detail.value.shipLength, //船舶
        shipType: that.data.shipTypeSelect, //船舶类型
        shipLoad: that.data.shipLoadSelect, //载重
        isAllMention: that.data.isAllMention,
        nineyards: formSubmitRes.detail.value.nineyards, //九位码
        arrivalTime: that.data.arrivalTime, //预计到站时间
        otherPhone: formSubmitRes.detail.value.otherPhone,
      };
    }

    const statusCode = new Map([
      [
        "0000",
        (msg, options) => {
          // 跳转新页面
          that.innerRouter(options.isDataChange, options.appleDetailDic);
        },
      ],
      [
        "0001",
        (msg, options) => {
          wx.showToast({
            title: msg,
            icon: "none",
          });
        },
      ],
      [
        "0003",
        async (msg, options) => {
          // wx.showModal(Object object) 支持 Promise 风格调用
          const modalResult = await wx.showModal({
            title: "提示",
            content: msg,
          });
          if (modalResult.confirm) {
            await that.addShip(options.paraDic);
            showMessage(await that.checkInfo(options.paraDic), options);
          }
        },
      ],
      [
        "0008",
        async (msg, options) => {
          const modalResult = await wx.showModal({
            title: "提示",
            content: msg,
          });
          if (modalResult.confirm) {
            options.paraDic.ignore = 1;
            showMessage(await that.checkInfo(options.paraDic), options);
          }
        },
      ],
      [
        "0010",
        async (msg, options) => {
          const modalResult = await wx.showModal({
            title: "提示",
            content: msg,
          });
          if (modalResult.confirm) {
            // 跳转新页面
            that.innerRouter(options.isDataChange, options.appleDetailDic);
          }
        },
      ],
    ]);

    // 除仅提示外的后端 code
    const showToastArr = ["0000", "0008", "0003", "0010"];

    // 根据请求后台得到的 code 处理不同逻辑
    const showMessage = (res, options) => {
      const code = res.data.code;
      [...statusCode].map(([key, value]) => {
        key === (!showToastArr.includes(code) ? "0001" : code)
          ? value.call(this, res.data.msg, options)
          : "";
      });
    };

    (async () => {
      const options = {};
      options.appleDetailDic = appleDetailDic;
      options.isDataChange = that.data.isDataChange;
      options.paraDic = paraDic;
      showMessage(await that.checkInfo(paraDic), options);
    })();
  },
});

Links to this note