Get data using await async without try catch

后端 未结 5 1816
抹茶落季
抹茶落季 2020-12-15 02:11

I am trying to use await-async without try-catch for this:

<
5条回答
  •  佛祖请我去吃肉
    2020-12-15 02:48

    A package I found called await-to-js can also help it.

    import to from 'await-to-js';
    
    const [err, users] = await to(getUsers());
    if(err) doSomething();
    

    The idea is like Lyes CHIOUKH's method, just a wrapper. Copied the source code here.

    /**
     * @param { Promise } promise
     * @param { Object= } errorExt - Additional Information you can pass to the err object
     * @return { Promise }
     */
    export function to (
      promise: Promise,
      errorExt?: object
    ): Promise<[U | null, T | undefined]> {
      return promise
        .then<[null, T]>((data: T) => [null, data])
        .catch<[U, undefined]>((err: U) => {
          if (errorExt) {
            Object.assign(err, errorExt);
          }
    
          return [err, undefined];
        });
    }
    
    export default to;
    

提交回复
热议问题