Cancelling ongoing http requests when next one is started - web app search feature This piece of code is aimed to cancel any ongoing search requests sent from the web application if next request is started, e.g. after user updates the search term. 

I tested it in the final application and everything looks fine. It has already been deployed to the remote environment in our organization.

It appears to work fine, but are there any pitfalls in the code?

const ongoingRequests = [];
const fetchData = (text, activePage, itemsPerPage) =&gt; async dispatch =&gt; {
dispatch({ type: FETCH_ENTITIES });
const page = activePage - 1;

let response;

// cancel any ongoing search requests
if (ongoingRequests.length &gt; 0) {
    ongoingRequests.map(x =&gt; x.cancel('next request started'));
    ongoingRequests.length = 0;
}

// start a new request
response = await (async () =&gt; {
    const cts = axios.CancelToken.source();
    ongoingRequests.push(cts);

    let path =
    text !== ''
        ? `/Search?PageNumber=${page}&amp;PageSize=${itemsPerPage}&amp;SearchTerm=${text}`
        : `?QueryLead=true&amp;PageNumber=${page}&amp;PageSize=${itemsPerPage}`;

    return axios
    .get(`${env_urls.api.entity}Entity${path}`, {
        cancelToken: cts.token,
    })
    .then(response =&gt; {
        return response;
    })
    .catch(error =&gt; {
        if (
        typeof cts !== 'undefined' &amp;&amp;
        typeof cts.token !== 'undefined' &amp;&amp;
        typeof cts.token.reason !== 'undefined' &amp;&amp;
        cts.token.reason.message === 'next request started'
        ) {
            // request cancelled, everything ok
        } else {
        throw error;
        }
    });
})();

// response is undefined if the request has been cancelled
if (typeof response !== 'undefined') {
    const data = response.data;

    dispatch({ type: FETCH_ENTITIES_SUCCESS, data });
}
};
You can rewritte this piece of code:

.catch(error =&gt; {
    if (
    cts !== 'undefined' &amp;&amp;
    cts.token !== 'undefined' &amp;&amp;
    cts.token.reason !== 'undefined' &amp;&amp;
    cts.token.reason.message === 'next request started'
    ) {
    } else {
    throw error;
    }
}


To:

.catch(error =&gt; {
    if (
        typeof cts === 'undefined' ||
        typeof cts.token === 'undefined' ||
        typeof cts.token.reason === 'undefined' ||
        cts.token.reason.message !== 'next request started'
    ) {
        throw error;
    }
}


And you can go further into the simplification using this trick.