Unexpected behavior with setTimeout - javascript

I have implemented an ajax polling function that I need to call continuously until the polling results come back with my expected results. In order to accomplish this, I am using setTimeout to introduce a delay so that the function doesn't just hammer the server with requests until it gets the results.
Let me preface this by saying that I have already found the way I need to implement the code to get the expected behavior I need. But, my question is in regards to the solution I found. I want to know why the solution worked with the timeout correctly, while the other one did not.
Here is the working code that successfully sets a timeout and polls for the result:
function makeRequest(url, data, requestType, successCallback, errorCallback, doneCallback) {
$.ajax({
url: url,
type: requestType,
data: data != null ? JSON.stringify(data) : '',
contentType: 'application/json; charset=utf-8',
success: function (success) {
if (successCallback) successCallback(success);
},
error: function (error) {
if (errorCallback) errorCallback(error);
},
done: function() {
if (doneCallback) doneCallback();
}
});
}
function pollForResult(Id) {
setTimeout(function () {
makeRequest('/Transaction/TransactionResult/' + Id,
null,
"GET",
function(result) {
//success code here
}, function(error) {
//error callback implementation here
if (error.status === 404) {
pollForResult(Id); //results not ready, poll again.
} else {
alert("stopped polling due to error");
}
}, null);
}, 2000);
}
Here is the code that doesn't properly set a timeout and just continually hits the server with requests:
function pollForResult(Id) {
makeRequest('/Transaction/TransactionResult/' + Id,
null,
"GET",
function(result) {
//success code here
}, function(error) {
//error callback implementation here
if (error.status === 404) {
setTimeout(pollForResult(Id), 2000); //results not ready, poll again.
} else {
alert("stopped polling due to error");
}
}, null);
}
So, my question is this: what is it about the second block of code that makes it continually poll the server for results instead of waiting the 2 seconds to poll again?
I suspect, although I haven't tried, that this would work properly in the second block of code:
setTimeout(function(){ pollForResult(Id); }, 2000); //results not ready, poll again.

setTimeout(pollForResult(transactionId),2000);
This code immediately calls pollForResult and assigns its return value to be the function called when the timeout occurs.
This is desired behaviour, because you might have a function that builds a closure and passes that to the timeout. However it seems to catch out a lot of people...
As you said, function() {pollForResult(transactionId);} will work just fine.

Related

JavaScript - Multiple Overlapping Async GET Requests?

I have tried ways to search for a solution but I can't seem to find the right combination of words or something... here goes:
I have an ASP.NET MVC application that users scan inventory/package barcodes into. Every time someone scans an item, I make an async request and then display a popup message with information about the package. This part works as expected and does not block the application during the request:
$.ajax({
type: 'GET',
dataType: 'json',
async: false,
url: '#Url.Action("SingleOrderLookup")?trackingNumber=' + trackingId,
success: function (result) {
if (result.success) {
var audio = findAudio(result.model, audioClips, saturdayAudio);
suppressDefaultSound = true;
var titleText = result.model.displayPromptText;
if (result.model.isRefrigerated) {
isRefrigerated = true;
titleText = "<p style='color: blue;'>(REFRIGERATED)</p>" + "<p>" + result.model.displayPromptText + "</p>";
}
swal.fire({
title: titleText,
text: "Place in route for " + result.model.displayPromptText,
type: "success",
showCancelButton: false,
confirmButtonText: "Sorted",
cancelButtonText: "Cancel",
timer: 1750,
preConfirm: function () {
return new Promise(function (resolve) {
resolve();
}, 1000);
}
}).then(result => {
if (result.value) {
}
});
var dupe = findOrderByTrackingNumber(trkNumbers, result.model.trackingId);
if (!dupe) {
trkNumbers.push({ trackingNumber: trackingId, depotId: result.model.destinationHub });
pkgCount++;
if ($("#divUpdatePickup").is(":hidden"))
$("#divUpdatePickup").show();
AddLogToTable(trackingId);
} else {
//audible feedback that duplicate was scanned
//if (!trkBin) PlayAudio(2);
//PlayAudio(2);
}
//playing audio
if (isRefrigerated) {
setTimeout(function () {
if (audio) playByteArray(audio);
}, 1500);
PlayRefrigerate();
} else {
if (audio) playByteArray(audio);
}
}
if (result.nullRoute) {
addToTrkNumbers = false;
Swal.fire({
title: "NO ROUTE DEFINED",
text: "Unable to match order to a route!",
type: "warning",
showCancelButton: false
});
}
}
});
However, I want the page to make another async call to populate a variable with an array of objects, transparently and without blocking the user from making scans and receiving information back from the async calls from the above code. This call should occur immediately when the page is loaded, and it could take more than a minute or two to receive all the data expected from this call. Once the response is back, the collection variable (zipSort[]) should be populated. The data in this variable will contain a "cache" of elements that the page can query against to avoid having to make individual server-side calls after each scan (in essence, I want to "front-load" data needed for the scan events and once completed, individual calls to the server should not be necessary since this variable should contain 99% of the IDs expected to be scanned).
This is where I'm having an issue and it's probably due to a lack of understanding of how async calls/JS promises work. Here is the code I have so far for this:
//array to hold data on expected tracking number scans
var zipSort = []
async function getCheckinGroup(zipSort) {
console.log("Fetching complete check-in group...");
var url = '/SortFacility/HubManager/GetOrders';
var promise = new Promise((resolve,reject) => {
$.ajax({
type: "GET",
url: url,
cache: false,
async: true,
contentType: "application/json",
success: function (result) {
if (result.success) {
console.log("Retrieval success");
try {
zipSort = result.model;
resolve(result.model);
} catch (ex) {
reject("Some error?");
}
} else {
reject("Some error?");
}
},
error: function (ob, errStr) {
reject("Something went wrong");
}
});
});
return promise;
}
//don't want this to hold up execution of the rest of the code, so zipSort[] should
//remain empty and get set transparently when the ajax response is returned:
getCheckinGroup(zipSort);
Every version of code I'm trying out from articles and tutorials I have read holds up the UI and keeps users from being able to scan items while the response hasn't been returned. What am I missing? How should I change this so that (a) users can begin scanning immediately once the page has loaded and receive information from individual async calls to the DB, and (b) zipSort[] can be populated with the totality of any data potentially needed for these scans, and once populated, scan events trigger a lookup on that variable instead of continued individual calls to the database?
Any help would be appreciated!
Edit: tried simply adding this call in-line and no matter where I put it, it blocks the other code from running until response is received, even though async is set to true:
$.ajax({
type: "GET",
url: url,
cache: false,
async: true,
contentType: "application/json",
success: function (result) {
console.log("Data received.");
zipSort = result.model;
}
});
Thanks everyone for your help. I found this little gem, which solved my problem:
https://josef.codes/c-sharp-mvc-concurrent-ajax-calls-blocks-server/
Applying [SessionState(System.Web.SessionState.SessionStateBehavior.Disabled)] to my controller class enabled concurrent async ajax calls.

JQuery AJAX - Filter before .done()

My application has a lot of AJAX calls, each of them return a JSON response. Instead of validating the data in each of the the .done() calls, I'm trying compact the code.
What we have so far
$.ajax({
url: 'test',
type: 'GET',
data: {
_token: token
},
dataFilter: function(jsonResponse) {
return isValidJson(jsonResponse);
}
}).done(function(jsonResponse) {
// do things
});
isValidJson(jsonResponse) {
try {
var parsedJson = $.parseJSON(jsonResponse);
if (parsedJson.error == 1) {
notificationController.handleNotification(parsedJson.message, 'error');
return false;
}
} catch (err) {
notificationController.handleNotification('A server-side error occured. Try refreshing if the problem persists.', 'error');
return false;
}
return jsonResponse; // Have to return the original data not true
}
The expected behavior is that if dataFilter returns false, it will trigger .fail(), if it returns true then it will continue to .done(). Instead, it just continues to .done() with the result of isValidJson().
Is there also a way to make .fail() do something standard like send a notification to the user without having to put it under every AJAX call?
Easiest way is to create a shorthand for $.ajax, by extending it.
Extending the AJAX call
jQuery.extend({
myAjax: function(params){
// Here we can modify the parameters and override them e.g. making 'error:' do something different
// If we want to add a default 'error:' callback
params.error = function() {
console.log('its failed');
};
// or you can specify data parse here
if (params.success && typeof params.success == 'function') {
var successCallback = params.success;
var ourCallback = function(responseJson) {
if (isValidJson(responseJson)) { // Validate the data
console.log('The json is valid');
successCallback(responseJson); // Continue to function
} else {
console.log('The json is not valid');
}
}
params.success = ourCallback;
}
return $.ajax(params);
}
});
Now everytime you want to make an AJAX call in your application, you DO NOT use $.ajax({}). Instead, you use $.myAjax({});
Example
$.myAjax({
url: 'domain.com',
type: 'GET',
success: function(data) {
// Do what you'd do normally, the data here is definitely JSON.
},
error: function(data) {}
});
And this special function will handle all errors same way, no need to write those validators every time.
Try to do it like this (Not tested):
var jxhr = $.ajax({
url: 'test',
type: 'GET',
data: {
_token: token
},
dataFilter: function(jsonResponse) {
if (!isValidJson(jsonResponse)) {
jxhr.abort();
}
return jsonResponse;
}
}).done(function(jsonResponse) {
// do things
});
By using this strategy - you are violating "separation of concern" strategy.
Ajax should resolve or reject according to its action. Not according if response is JSON or not.
A possible solution : ( sure there are also another solutions)
function GetSanitized(d) {
return d.then(function(a) {
if (a.indexOf('{') > -1) //check if json ( just for example)
return $.Deferred().resolve(JSON.parse(a)); //return object
else
return $.Deferred().reject(a); //reject
},
function() {
return $.Deferred().reject("ajax error"); //ajax failed
}
);
}
var ajax = $.Deferred();
GetSanitized(ajax) .then(function (a){alert(" Json p's value is "+a["p"]);},function (a){alert("Error"+a);});
ajax.resolve("{\"p\":2}"); //simulate ajax ok , valid json
//ajax.resolve("\"p\":2}"); //simulate ajax ok , invalid json
//ajax.reject("\"p\":2}"); //simulate ajax bad , valid json
http://jsbin.com/vozoqonuda/2/edit

Jquery Ajax Server Polling; Polling the server based on an earlier ajax response

What I am trying to do:
1. Initially gives an ajax request to the server based on some inputs
2. The server returns a job id generated by RQ (Python-rq)
3. Based on the job id ajax request made to a url constructed with the jobid regularly till a valid response is obtained
What I have:
$.ajax({
type: "POST",
url: "/start",
data:{crop: valueCrop, state: valueState, variablemeasure: valueVariable, unit:unitMeasure, from:yearFrom, to:yearTo},
success: function(results) {
console.log(results);
var jobId='';
jobId = results;
function ajax_request() {
$.ajax({
type: "GET",
url: "/results/" + jobId,
dataType: "json",
success:function(xhr_data) {
if (xhr_data == {"status":"pending","data":[]}){
console.log("Waiting for response");
setTimeout(function() { ajax_request(); }, 2000);
} else {
console.log(xhr_data);
}
},
error:function(error) {
console.log(error)
}
});
}
},
error: function(error) {
console.log(error)
}
})
Is this even possible? I am not getting any output at all on the console although the rq says the job is finished. I think it is not entering that if loop. When I visit the "/results/jobId" url I am able to see the result.
Please help.
I see a few bugs in this code. First of all, you have defined the function ajax_request(). But you are not calling it. You can call it at the end of its definition.
Secondly, this code is problematic:
if (xhr_data == {"status":"pending","data":[]})
The object notation creates another object which is definitely not equal to xhr_data.
You can do:
if (xhr_data.status === "pending")

Synchronous Ajax requests "lock" browser

I have a couple of jQuery Ajax requests, which have to be synchronous, but they keep locking/freezing the browser, until the response is received. My main problem is, that until the response is received I have to display a spinning icon, but due to the freezing the spinner is not displayed and even if it miraculously is it doesn't animate.
This is the event displaying the spinner and sending the request:
$(document).on('click', '#open-button', function () {
var input = "some text";
var wrapper = $('#wrapperWindow');
wrapper.children().animate({
opacity: 0
}, 500);
wrapper.children().remove();
wrapper.append('<div id="loading-spinner" style="display:none;"></div>');
var spinner = $('#loading-spinner');
spinner.css({
backgroundImage: 'url("img/loading.gif")',
opacity: 0
});
spinner.show();
spinner.animate({
opacity: 1
}, 500);
var dataForTab = requestData(input); //<-- the request
if (dataForTab.length > 0) {
//do stuff
}
});
The request:
function requestData(input) {
var result = null;
$.ajax({
async: false,
type: "POST",
url: "/some/url?input=" + input,
dataType: "json",
retryLimit: 3,
success: function (json) {
result = json;
},
error: function (xhr, err) {
console.log(xhr);
console.log(err);
}
});
return result;
}
Until the request returns the received JSON data, everything stops moving. How can I fix this please?
That's the essence of synchronous requests, they are locking. You may want to try to move the requests to a web worker. Here's an example (not using XHR, but it can give you an implementation idea)
A web worker is implemented in a separate file, the scripting can look like:
onmessage = function (e) {
var result = null;
$.ajax({
async: false,
type: "POST",
url: "/some/url?input=" + input,
dataType: "json",
retryLimit: 3,
success: function (json) {
result = json;
postMessage({result: result});
},
error: function (xhr, err) {
postMessage({error: err});
}
});
}
Depending on your use case you can use something like
task.js Simplified interface for getting CPU intensive code to run on all cores (node.js, and web)
A example would be
// turn blocking pure function into a worker task
const syncWorkerRequest = task.wrap(function (url) {
// sync request logic
});
// run task on a autoscaling worker pool
syncWorkerRequest('./bla').then(result => {
// do something with result
});
You should not be doing this though, unless you need to do some heavy data processing, please use async requests.

JQuery ajax call never triggers error handler

I have an Ajax call that is called once and then it calls itself recursively in order to manage a newsletter send job (the send is managed by the send.php script). The call works pretty well (generally for the first 15-20 mins it goes well), the only problem is that sometime the call never returns but it does not trigger the error function that you can see inside the ajax call. Infact the alert is never called and the "SEND ERROR!!" message is never displayed. What can be the problem?
The following is the interested function:
function _ajax_send(id_send, curr_index)
{
$.ajax({
type: "POST",
url: "ajax/send.php",
data: { id: id_send, index: curr_index },
async: true,
dataType: "json",
global: true,
timeout: 130000,
erorr: function(xhr, status, error) {
alert("SEND ERROR!!");
setTimeout(function(){ _ajax_send(<?php echo $_GET['id']; ?>, Number(sent)); }, 3000);
},
success: function(data) {
if(data.result) {
if(!data.completed)
{
calls = calls + 1;
_ajax_send(id_send, data.curr_index);
}
else
{
done = true;
}
}
else
{
alert("Logic Error. Cause: " + data.error);
}
}
});
}
Thank you very much for any help ;)

Categories