AJAX: Asyncronous calls in Javascript to Java - javascript

I currently have a few basic question with asynchronous calls in JS.
I have searched and found a similar question posted in the past here:
Parallel Ajax Calls in Javascript/jQuery
But I still have some doubts about asynchronous calls.
Let´s say that I make it asynchronous using a jQuery when to join both flows when both AJAX calls are finished. What would happen if one of the AJAX calls fail?
Some of the calls that I need to make should be asynchronous only in some cases. Is it a good practice to make the type of call (asynchronous true or false) variable? Or doesn't it really matter to have an asynchronous true call when there is only one JS flow?
If I need to do a few database calls with my asynchronous methods (different tables). Could I have a conflict if i make two database calls at the same time because make my AJAX asynchronous? I am quite new to asynchronous calls. (SQL database) (Spring Boot Java 8)
The basic flow would be something like this:

Ths answer is a compilation of everything told in the comments, not my own.
You handle it in your code.
Synchronous calls are deprecated, so never make a synchronous ajax call - the first A in AJAX actually stands for Asynchronous, so a Synchronous AJAX request makes no sense anyway (though of course it is a thing)
It is the same in Java as most other systems: the backend may process your calls in a different order or even truly in parallel (think a cluster, one call is processed from one node, the other call fro another node). So it depends on your semantics: if one depends on the outcome of the other, then you should make sure they are only called sequentially. If they both contribute independently to the final outcome, then you have to make sure to revert the effects of the one, if the other fails. There are many ways to do that - and maybe it should be a responsibility of the backend.

Related

Requesting all results (synchronously) from cursor paginated APIs

I need to collect all pages from an API that uses cursor-based pagination. Each call returns (in addition to a page of data) a boolean 'hasNext' and a key 'after'. If 'hasNext' is true, the next request passes 'after' to indicate where the next result should start.
Since each call is dependent on the result of the previous one, it seems this must be done synchronously. I can probably use XMLHttpRequest to make synchronous calls, but I often see comments that say synchronous requests are being deprecated and fetch is for asynchronous requests only.
Any suggestions on how to handle synchronous requests (where each request is dependent on the result of the previous one and the results need to be in order)?
I've seen several methods for handling paginated APIs, but they all seem to apply to offset pagination.

When shall one make a function return a promise? [duplicate]

This question already has answers here:
Javascript: How to determine whether to promisefy a function?
(2 answers)
Closed 4 years ago.
I'm getting into generators and promises now and I've kind of gotten the handle of how they work. Now it's time to make my own functions which utilize these. There are guides out there explaining how to make them and what they are for but however they rarely discuss the appropriate times when one should be used.
I know this mainly has to lie with promises as generators just help the code writing look synchronous (among other things).
So my question is: When should I and when should I not promisify a function I have?
From my understanding if the cpu is being utilized 100% by the function then I should NOT promisify as there is no point.
If the cpu is being blocked and is waiting for something external such as waiting for something to download then I guess I should promisify that function.
Promises should be used when you have asynchronous operations that you want to execute in a sequence. Operations that are costly, like writing to a file/db, making a request to another service, so forth, usually have an asynchronous api, since doing those synchronously would block your single-threaded javascript application. In those cases, you either use something like promises for a cleaner code, you use named functions and explicitly call them one after the other as callbacks or you don't use anything and have yourself a pyramid of doom full of callbacks.
So, imagine you want to get the user data from the token you recieve in the http request, then get all the posts regarding him, and get a special holiday offer from one of your other services that you wanna stick in there with the request. With promises, you could do something like
router.get('/activities', function(req, res){
userRepo.findByToken(token).then(checkForOffer).then(activityRepo.getUserPosts).then(function(composite){
res.send({activities: composite.activities, offer: composite.offer});
}).fail(function(err){
//handle the error
});
})
This post paint a clearer picture of how and when you should use promises.

Why is synchronous module loading in javascript that bad

I know that the synchronous ajax calls on the main thread are deprecated, but I still wonder why.
How do you archive this in asynchronous module loading: get('moduleDependency').foo(); ?
I would like to use this kind of synchronous calls at least in development to speed up the overall development circle. The modules are in production already concatenated into one file and will never touch the synchronous loading function at all.
My synchronous module loader (~80 loc) solves dependencies and more. I rewrote it to asynchronous loading, and it's working fine... but I'll have to give up using code like: get('moduleDependencie').foo();
And that's really a mess!
How do you get this kind of calls working with asynchronous loading? Or do I simply have to use asynchronous loading in cooperation with a while(true) function on the main thread in the future - until they ban while loops on the main thread also?
As long as the synchronous call isn't finished or a timeout isn't reached, there is no possibility for user to interact with the page. So it can hang up and in worst case the user has to restart his browser. Asynchronous programming and scripting is based on callbacks. You just have to bind a method to the success handler of the AJAX-Request. You can use
success:function(result){
//do something
}
or
success: myfunction
[...]
function myfunction(result){
//do something
}
Once the asynchronous code has finished, this method will be called. So put everything that works with the data from the AJAX request into this method.

Node js wrap async function

I'm implementing an API which has a function:
get(url)
Which returns a Response Object, i.e. no callback. The Http Modules I have found implements node-style async functions with callbacks. I have tried to wait for the async function to return in several ways, using Fibers etc. Fibers solves the issue within the Fiber, but can't be used in my case as I need to return the value outside any Fiber.
It might be possible to wrap the Entire Execution (including the code using the API) but I really don't want this. Is there any module that does what I want?
If I understand the question, that you're trying to mix asynchronous code with synchronous code what you're trying to accomplish is not really possible without promises. As soon as you mix asynchronous code with synchronous code, you make the entire code asynchronous, or you risk the synchronous code returning a value before the result from the synchronous code is returned.
You could always try a timeout on the function that holds it returning until a given time period has expired, which hopes that the asynchronous code executes and has a return value before the synchronous code returns. However, this is extremely inefficient, and does not eliminate the problem as you could still end up returning before the asynchronous portion has finished.
I'd also agree with the comment from robertklep that node.js really does not fit your use case, and you might be better looking at another tool for the job.

When is it appropriate to use synchronous ajax?

I was just reading another question about jQuery's synchronous ajax call, and I got to wondering:
What circumstances make a synchronous version of an ajax call beneficial/necessary?
Ideally I'd like an example, and why synchronous is better than standard ajax.
The only reasonable example I can think of (that can't be worked around another way) is making a call in window.onbeforeunload, where you need it to be synchronous, or the page will move on and the request will never complete.
In this specific case using standard/asynchronous behavior, you're all but assured the request will die too early to have any impact, or ever contact the server.
I'm not saying I'm in favor of doing this, quite the opposite (as it negatively impacts the user's browsing speed). But...there's not much option here.
In sum, please do not use synchronous requests as #Brandon says: they are a cheap/easy/quick way to avoid making a callback. In addition, modern browsers show warnings if synchronous requests are made and we do not like that. Make your world asynchronous.
synchronous ajax is often used to retrieve a valued from the server which is required to further continue processing of client side code. in such case, the ajax call will block until the call returns with the desired value. example:
a javascript function needs to compute salary for an employee:
step1 : get the employee id from the form
step2 : make a sync server call passing the emp.id to get his salary/hour
step3 : multiply salary rate by number of working hours
as you can see, total salary cannot be computed unless the server call is finished so this should be a sync function, although if using jquery, one could handle onSuccess to compute the salary asynchronously but processing will continue in this if you have a message box to display the salary, it will appear empty...
I would venture a guess that it'd be good in a scenario where you want to perform some ajax calls but you have one call that relies on the results of another call. If you perform them synchronously you can wait for the independent to finish before the dependent call fires.

Categories