封装promise请求接口,错误处理方法

本例子实现了封装promise请求接口,错误处理方法,具体代码如下

export const to = function (promise: unknown) {
  // @ts-ignore
  if (!promise || !Promise.prototype.isPrototypeOf(promise)) {
    return new Promise((_resolve, reject) => {
      reject(new Error("request promises as ths param"));
    }).catch((error) => {
      return [error, null];
    });
  }

  // @ts-ignore
  // eslint-disable-next-line func-names
  return (promise as any)
    .then(function () {
      // eslint-disable-next-line prefer-rest-params
      return [null, ...arguments];
    })
    .catch((error: unknown) => {
      return [error, null];
    });
};

具体使用如下:

const resp = await to(Taro.getImageInfo({ src: '参数'}));

你可能感兴趣的:(前端,javascript,servlet)