asyncfunction

ES2017 introduces async functions to make asynchronous operations and use more convenient. Asynchronous code can be written as if it were synchronous code.

// Regular Promise
fetchPageData()
    .then((pageDataResponse) = > {
        const { data } = pageDataResponse;
        setPageData(data);
    });

// Use async
const getPageData = async() = > {const pageDataResponse = await fetchPageData();
    const { data } = pageDataResponse;
    setPageData(data);
};
Copy the code

Error handling

Although async functions simplify asynchronous operations, it is troublesome to handle errors when exceptions occur.

  1. try... catchError handling: willawaitError wrapped intry... catchCode block, for exception catching.
const getPageData = async() = > {try {
        const pageDataResponse = await fetchPageData();
        const { data } = pageDataResponse;
        setPageData(data);
    } catch (e) {
        console.log('page data fetch error ', e); }};Copy the code
  1. promise reject catchError handling:asyncThe function returns aPromiseObject, which internally throws an error that will result in a returnPromiseObject torejectStatus, can passcatchThe function undergoes an error.
const getPageData = async() = > {const pageDataResponse = await fetchPageData().catch((e) = > {
        console.log('page data fetch error ', e);
    });
    const { data } = pageDataResponse;
    setPageData(data);
};
Copy the code

It is possible to use these error handlers for a single async function, but not very elegant when multiple async functions need to be handled. Especially if the error handling for each async function is not consistent, it can be intolerable for code cleanliness freaks.

const getDisplayData = async() = > {try {
        const data1 = await fetchData1();
        const data2 = awaitfetchData2(); . }catch (e) {
        console.log('error catch ', e); }};Copy the code

Await-to-js error handling

How to write async await without try-catch blocks in Javascript How to gracefully use async and await in Javascript. The await-to-js library is recommended for detailed description and can also be used via an NPM installation. The code is also relatively simple. The async function returns a Promise object and performs a unified wrap processing on the Promise object, which includes catch exception handling.

/ * * *@param { Promise } promise
 * @param { Object= } errorExt - Additional Information you can pass to the err object
 * @return { Promise }* /
export function to<T.U = Error> (
  promise: Promise<T>, errorExt? :object
) :Promise"[U.undefined"|"null.T] >{
  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;
Copy the code

Use await-to-js for asynchronous operations.

import to from 'await-to-js';

const fetchData1 = async() = > {};const fetchData2 = async() = > {};const fetchPageData = async() = > {const data1 = to(fetchData1());
    const data2 = to(fetchData2());
    const [error1, res1] = data1;
    const [error2, res2] = data1;
    if (res1) {}
    if (error1) {}
    if (res2) {}
    if (error2) {}
};
Copy the code

Furthermore, we can repackage await-to-JS for business use.

import to from 'await-to-js';

const awaitWrap = async <T, U = Error>(
    promise: Promise<T>, onSuccess? : (data: T) =>void, onError? : () = >void, errorExt? :object.) = > {
    const handleError = onError || defaultErrorFn;
    const handleSuccess = onSuccess || defaultSuccessFn;
    const res = await to<T, U>(promise, errorExt);
    const [data, error] = res;
    onSuccess(data);
    onError(error);
};
Copy the code

Use awaitWrap for asynchronous operations.

const fetchData1 = async() = > {await awaitWrap(
        fetch('/data1'),
        (data) = > {
            setData1(data);
        },
        (error) = > {
            const{ message } = error; toast.error(message); }); };const fetchData2 = async() = > {await awaitWrap(
        fetch('/data2'),
        (data) = > {
            setData2(data);
        },
        (error) = > {
            const{ message } = error; toast.error(message); }); };const fetchPageData = async() = > {await fetchData1();
    awaitfetchData2(); . };Copy the code

In summary, async await exception handling is not just a try… Catch can also make exception handling more elegant by extracting and encapsulating async await exception handling.