Cancelling ongoing http requests when next one is started - web app search feature











up vote
3
down vote

favorite
1












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) => async dispatch => {
dispatch({ type: FETCH_ENTITIES });
const page = activePage - 1;

let response;

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

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

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

return axios
.get(`${env_urls.api.entity}Entity${path}`, {
cancelToken: cts.token,
})
.then(response => {
return response;
})
.catch(error => {
if (
typeof cts !== 'undefined' &&
typeof cts.token !== 'undefined' &&
typeof cts.token.reason !== 'undefined' &&
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 });
}
};









share|improve this question









New contributor




michal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 1




    "Does it work as intended?" : it's up to you to tell us :]
    – Calak
    2 days ago










  • @Calak Everything is fine when I test it in the application but maybe there is an issue that I cannot see. Like some js construct that makes no sense ;)
    – michal
    2 days ago










  • "Does it work as intended?" Did you test it? One of the prerequisites of posting on Code Review is that the code has to work to the best of your knowledge. Does it? You say it works in the application. Is that the final application that needs it? A test application?
    – Mast
    2 days ago






  • 1




    @Mast I have updated the question.
    – michal
    2 days ago






  • 1




    When I implement this type of search functionality I usually cancel the current request when the user presses a key (on the keypress, paste events) and start a timer for a fraction of a second. I only start the request when the timer expires. That way I don't start requests while the user is still typing. I've also rarely found it unnecessary to keep an array of requests. I just keep the currently executing one if any.
    – Marc Rohloff
    2 days ago















up vote
3
down vote

favorite
1












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) => async dispatch => {
dispatch({ type: FETCH_ENTITIES });
const page = activePage - 1;

let response;

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

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

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

return axios
.get(`${env_urls.api.entity}Entity${path}`, {
cancelToken: cts.token,
})
.then(response => {
return response;
})
.catch(error => {
if (
typeof cts !== 'undefined' &&
typeof cts.token !== 'undefined' &&
typeof cts.token.reason !== 'undefined' &&
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 });
}
};









share|improve this question









New contributor




michal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 1




    "Does it work as intended?" : it's up to you to tell us :]
    – Calak
    2 days ago










  • @Calak Everything is fine when I test it in the application but maybe there is an issue that I cannot see. Like some js construct that makes no sense ;)
    – michal
    2 days ago










  • "Does it work as intended?" Did you test it? One of the prerequisites of posting on Code Review is that the code has to work to the best of your knowledge. Does it? You say it works in the application. Is that the final application that needs it? A test application?
    – Mast
    2 days ago






  • 1




    @Mast I have updated the question.
    – michal
    2 days ago






  • 1




    When I implement this type of search functionality I usually cancel the current request when the user presses a key (on the keypress, paste events) and start a timer for a fraction of a second. I only start the request when the timer expires. That way I don't start requests while the user is still typing. I've also rarely found it unnecessary to keep an array of requests. I just keep the currently executing one if any.
    – Marc Rohloff
    2 days ago













up vote
3
down vote

favorite
1









up vote
3
down vote

favorite
1






1





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) => async dispatch => {
dispatch({ type: FETCH_ENTITIES });
const page = activePage - 1;

let response;

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

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

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

return axios
.get(`${env_urls.api.entity}Entity${path}`, {
cancelToken: cts.token,
})
.then(response => {
return response;
})
.catch(error => {
if (
typeof cts !== 'undefined' &&
typeof cts.token !== 'undefined' &&
typeof cts.token.reason !== 'undefined' &&
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 });
}
};









share|improve this question









New contributor




michal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











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) => async dispatch => {
dispatch({ type: FETCH_ENTITIES });
const page = activePage - 1;

let response;

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

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

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

return axios
.get(`${env_urls.api.entity}Entity${path}`, {
cancelToken: cts.token,
})
.then(response => {
return response;
})
.catch(error => {
if (
typeof cts !== 'undefined' &&
typeof cts.token !== 'undefined' &&
typeof cts.token.reason !== 'undefined' &&
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 });
}
};






javascript beginner axios






share|improve this question









New contributor




michal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




michal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 2 days ago









Mast

7,43863686




7,43863686






New contributor




michal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 2 days ago









michal

163




163




New contributor




michal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





michal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






michal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 1




    "Does it work as intended?" : it's up to you to tell us :]
    – Calak
    2 days ago










  • @Calak Everything is fine when I test it in the application but maybe there is an issue that I cannot see. Like some js construct that makes no sense ;)
    – michal
    2 days ago










  • "Does it work as intended?" Did you test it? One of the prerequisites of posting on Code Review is that the code has to work to the best of your knowledge. Does it? You say it works in the application. Is that the final application that needs it? A test application?
    – Mast
    2 days ago






  • 1




    @Mast I have updated the question.
    – michal
    2 days ago






  • 1




    When I implement this type of search functionality I usually cancel the current request when the user presses a key (on the keypress, paste events) and start a timer for a fraction of a second. I only start the request when the timer expires. That way I don't start requests while the user is still typing. I've also rarely found it unnecessary to keep an array of requests. I just keep the currently executing one if any.
    – Marc Rohloff
    2 days ago














  • 1




    "Does it work as intended?" : it's up to you to tell us :]
    – Calak
    2 days ago










  • @Calak Everything is fine when I test it in the application but maybe there is an issue that I cannot see. Like some js construct that makes no sense ;)
    – michal
    2 days ago










  • "Does it work as intended?" Did you test it? One of the prerequisites of posting on Code Review is that the code has to work to the best of your knowledge. Does it? You say it works in the application. Is that the final application that needs it? A test application?
    – Mast
    2 days ago






  • 1




    @Mast I have updated the question.
    – michal
    2 days ago






  • 1




    When I implement this type of search functionality I usually cancel the current request when the user presses a key (on the keypress, paste events) and start a timer for a fraction of a second. I only start the request when the timer expires. That way I don't start requests while the user is still typing. I've also rarely found it unnecessary to keep an array of requests. I just keep the currently executing one if any.
    – Marc Rohloff
    2 days ago








1




1




"Does it work as intended?" : it's up to you to tell us :]
– Calak
2 days ago




"Does it work as intended?" : it's up to you to tell us :]
– Calak
2 days ago












@Calak Everything is fine when I test it in the application but maybe there is an issue that I cannot see. Like some js construct that makes no sense ;)
– michal
2 days ago




@Calak Everything is fine when I test it in the application but maybe there is an issue that I cannot see. Like some js construct that makes no sense ;)
– michal
2 days ago












"Does it work as intended?" Did you test it? One of the prerequisites of posting on Code Review is that the code has to work to the best of your knowledge. Does it? You say it works in the application. Is that the final application that needs it? A test application?
– Mast
2 days ago




"Does it work as intended?" Did you test it? One of the prerequisites of posting on Code Review is that the code has to work to the best of your knowledge. Does it? You say it works in the application. Is that the final application that needs it? A test application?
– Mast
2 days ago




1




1




@Mast I have updated the question.
– michal
2 days ago




@Mast I have updated the question.
– michal
2 days ago




1




1




When I implement this type of search functionality I usually cancel the current request when the user presses a key (on the keypress, paste events) and start a timer for a fraction of a second. I only start the request when the timer expires. That way I don't start requests while the user is still typing. I've also rarely found it unnecessary to keep an array of requests. I just keep the currently executing one if any.
– Marc Rohloff
2 days ago




When I implement this type of search functionality I usually cancel the current request when the user presses a key (on the keypress, paste events) and start a timer for a fraction of a second. I only start the request when the timer expires. That way I don't start requests while the user is still typing. I've also rarely found it unnecessary to keep an array of requests. I just keep the currently executing one if any.
– Marc Rohloff
2 days ago










1 Answer
1






active

oldest

votes

















up vote
0
down vote













You can rewritte this piece of code:



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


To:



.catch(error => {
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.






share|improve this answer



















  • 1




    imo, you shouldn't use typeof you should just write it as if (cts === undefined) || ...
    – Marc Rohloff
    2 days ago










  • @MarcRohloff yeah, copy/paste's mistake :p Thx
    – Calak
    2 days ago











Your Answer





StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");

StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});






michal is a new contributor. Be nice, and check out our Code of Conduct.










 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208275%2fcancelling-ongoing-http-requests-when-next-one-is-started-web-app-search-featu%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
0
down vote













You can rewritte this piece of code:



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


To:



.catch(error => {
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.






share|improve this answer



















  • 1




    imo, you shouldn't use typeof you should just write it as if (cts === undefined) || ...
    – Marc Rohloff
    2 days ago










  • @MarcRohloff yeah, copy/paste's mistake :p Thx
    – Calak
    2 days ago















up vote
0
down vote













You can rewritte this piece of code:



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


To:



.catch(error => {
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.






share|improve this answer



















  • 1




    imo, you shouldn't use typeof you should just write it as if (cts === undefined) || ...
    – Marc Rohloff
    2 days ago










  • @MarcRohloff yeah, copy/paste's mistake :p Thx
    – Calak
    2 days ago













up vote
0
down vote










up vote
0
down vote









You can rewritte this piece of code:



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


To:



.catch(error => {
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.






share|improve this answer














You can rewritte this piece of code:



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


To:



.catch(error => {
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.







share|improve this answer














share|improve this answer



share|improve this answer








edited 2 days ago

























answered 2 days ago









Calak

1,939314




1,939314








  • 1




    imo, you shouldn't use typeof you should just write it as if (cts === undefined) || ...
    – Marc Rohloff
    2 days ago










  • @MarcRohloff yeah, copy/paste's mistake :p Thx
    – Calak
    2 days ago














  • 1




    imo, you shouldn't use typeof you should just write it as if (cts === undefined) || ...
    – Marc Rohloff
    2 days ago










  • @MarcRohloff yeah, copy/paste's mistake :p Thx
    – Calak
    2 days ago








1




1




imo, you shouldn't use typeof you should just write it as if (cts === undefined) || ...
– Marc Rohloff
2 days ago




imo, you shouldn't use typeof you should just write it as if (cts === undefined) || ...
– Marc Rohloff
2 days ago












@MarcRohloff yeah, copy/paste's mistake :p Thx
– Calak
2 days ago




@MarcRohloff yeah, copy/paste's mistake :p Thx
– Calak
2 days ago










michal is a new contributor. Be nice, and check out our Code of Conduct.










 

draft saved


draft discarded


















michal is a new contributor. Be nice, and check out our Code of Conduct.













michal is a new contributor. Be nice, and check out our Code of Conduct.












michal is a new contributor. Be nice, and check out our Code of Conduct.















 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208275%2fcancelling-ongoing-http-requests-when-next-one-is-started-web-app-search-featu%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Ellipse (mathématiques)

Quarter-circle Tiles

Mont Emei