@actualwave/resolve-or-timeout 中文文档教程

发布于 3年前 浏览 10 项目主页 更新于 3年前

@actualwave/resolve-or-timeout

在 Promise.race() 中运行的函数是您的承诺和超时,如果超时先完成,则结果承诺会因错误而拒绝。

export const resolveOrTimeout = <T = unknown>(

  // Promise or a function that will be passed to a Promise object
  promiseOrHandler:
    | Promise<T>
    | ((
        resolve: (data: T) => void,
        reject?: (data: unknown) => void
      ) => unknown),

  // timeout in milliseconds. if 0, race condition will not apply and original promise will be returned as is
  timeout: number, 

  // optional, timeout error message
  timeoutError?: string, 

  // optional callback that will be executed when timeout completes first
  onTimeout?: (msg: string) => void 
) => Promise<T>;

Example

try {
  /*
    if request resolves in less than 500 ms, you will get response
  */
  const response = await resolveOrTimeout(
    fetch('/super/long/request'),
    500,
    'Sorry, your request takes toooooo long.',
  );
} catch (error) {
  /*
    if request takes longer than 500 ms, promise rejects with error message
  */
}

它接受承诺或将传递给承诺的函数。

const response = await resolveOrTimeout(
  (resolve) => {
    // do something then resolve
  },
  500
);

@actualwave/resolve-or-timeout

Function that runs in Promise.race() your promise and a timeout, if timeout completes first, resulting promise rejects with error.

export const resolveOrTimeout = <T = unknown>(

  // Promise or a function that will be passed to a Promise object
  promiseOrHandler:
    | Promise<T>
    | ((
        resolve: (data: T) => void,
        reject?: (data: unknown) => void
      ) => unknown),

  // timeout in milliseconds. if 0, race condition will not apply and original promise will be returned as is
  timeout: number, 

  // optional, timeout error message
  timeoutError?: string, 

  // optional callback that will be executed when timeout completes first
  onTimeout?: (msg: string) => void 
) => Promise<T>;

Example

try {
  /*
    if request resolves in less than 500 ms, you will get response
  */
  const response = await resolveOrTimeout(
    fetch('/super/long/request'),
    500,
    'Sorry, your request takes toooooo long.',
  );
} catch (error) {
  /*
    if request takes longer than 500 ms, promise rejects with error message
  */
}

It accepts promise or a function that will be passed to a promise.

const response = await resolveOrTimeout(
  (resolve) => {
    // do something then resolve
  },
  500
);
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文