1

I'm aware that "do-while" will run atleast once compared to "while" which has to satisfy a condition to run.

Is this correct usecase of do-while?

do{
  var ajaxresponse = make an ajax call and assign the response to the variable.
while( ajaxresponse.length == <some number>);
3
  • 4
    No. AJAX = Asynchronous .... Commented Mar 16, 2016 at 4:25
  • ^ Loop = synchronous Commented Mar 16, 2016 at 4:27
  • @FelixKling: do { await fetch(…); } while (…) :-P Commented Mar 16, 2016 at 4:32

3 Answers 3

1

For iterating and performing operations on response data, it's better to do that in callback function. Because AJAX is asynchronous. Following code uses Jquery for Ajax request.

$.ajax({
  method: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
})
  .done(function( ajaxresponse ) {

    do{
    //operations
    }while(ajaxresponse.length == <some number> );

  });
Sign up to request clarification or add additional context in comments.

Comments

1

If you were to make the AJAX call synchronous, this would be valid.

ex.

$.ajax({url:"url",..., async: false});

BUT, this totally defeats the point of AJAX being asynchronous, so should be avoided.

Comments

0

No.

When JavaScript runs in a web client, it runs synchronously - meaning only one thread of execution for JavaScript is possible at a time.

Because of this, if a function makes a call for an asynchronous operation to be performed (like XmlHttpRequest.send or setTimeout), that operation is handled via a WebAPI by the browser OUTSIDE of the JavaScript runtime in a separate thread and the callbacks for that operation are then queued up and are executed when the JavaScript runtime is idle.

In your code:

do{
  var ajaxresponse = make an ajax call and assign the response to the variable.
while( ajaxresponse.length == <some number>);

the ajaxresponse won't come back until the function containing the do/while loop completes, so when your while condition checks the ajaxresponse, there won't be a value to check.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.