Friday, September 28, 2018

jquery - Can you wait for javascript callback?




I'm trying to use the jQuery alerts dialog library from http://abeautifulsite.net/notebook/87 instead of the default alerts (which look pretty awful in my opinion). This seems to be a great library, but there is not an example of how to use the jConfirm library.



I need to do something like this:



function confirm() {
var result = false;
var response = false;
jConfirm('are you sure?', 'Confirmation Dialog',
function(r) {

result = r;
response = true;
return r;
});
if (response == true) {
alert(result);
return result;
}
else {
//wait for response

alert('hi');
}
}


and my call from my .net button:



I've posted a comment on the plugin's website (just this morning) and did Google searches for javascript and waiting for a callback to complete with no results.




Any ideas on how to use the callback correctly to get the result, before the rest of the javascript executes?



Thanks.


Answer



jConfirm('are you sure?', 'Confirmation Dialog',
function(r) {
result = r;
response = true;
return r;
}

);
if (response == true) {


This betrays a misunderstanding of the sequence of events that occurs using asynchronous code. Just because you've written it inline doesn't mean it's going to execute strictly top-to-bottom.




  1. jConfirm is called, receiving a function as one of its parameters, which it remembers.

  2. jConfirm displays its UI on the page and returns immediately.

  3. The 'if (response==true)' line executes. Really this should just read 'if (response)', the boolean comparison is superfluous. But in any case response is of course false. Your function gives up and exits, giving control back to the browser.


  4. The user clicks jConfirm's UI.

  5. jConfirm only now jumps into action and calls back the function you gave it and it remembered earlier.

  6. Your nested function sets response true, far too late for the 'if (response==true)' condition to do anything with it.



You have written "//wait for response" as an alternative, but there is no JavaScript code you can write that will actually do that. Your function must return to give control back to the browser, before the browser can fire the click events on the jConfirm UI that make processing proceed.



Ways to make asynchronous code work in a synchronous context (and vice versa) exist - in particular threads and coroutines (and their limited relation generators). But JavaScript has none of these features, so you must write your code to fit the synchronous-or-asynchronous model your library is using.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...