Giorgi Moniava
Giorgi Moniava

Reputation: 28654

Dealing with a certain async situation in JavaScript

Imagine I have such setup. Imagine I have some map on my page and next to it there is a dialog where there is a toggle button.

Problem

Imagine two situations:

I hope you can see the pattern of the kind of problems I am encountering here. What is the best practice to deal with such situations?

Upvotes: 2

Views: 155

Answers (2)

Marko Gresak
Marko Gresak

Reputation: 8207

What you're describing is a simple case of race conditions.

There is no general solution for this kind of problem, it needs to be handled case-by-case. But in most cases, you probably want to display the results of the latest action user has done. If you don't have another way of knowing which request is which, you can attach some sort of identifier to the request, for example a GUID, and only display the data when the corresponding request is done.

Sometimes, the solution can be simply to disable all actions which could cause a race condition for the duration of the request, but this can deteriorate the user experience. Take for example Google Docs online editor, imagine that the whole editor would get disabled every time the auto-save function is triggered. In cases like this, it would be beneficial to store every update and compose the state from these actions. One of JavaScript that does state management like this is Redux. If you want to store data like this, you could use a database, such as EventStore.

Upvotes: 1

Tushar Gupta
Tushar Gupta

Reputation: 15913

I have solutions in my mind. One has the impact on User Experience and UI, the other one involves sending the last request. I will explain how:

1. Disabling the map and the button until the request is complete.

So what you can do is a loading or overlay div that stays until the request info is returned. Until this, the user is not allowed to use the map or toggle. This is UI impact but I have seen sites behaving this manner.

2. Map position. The other option is to store the map position in like local storage and match the map position again on request success. If the map is on a different position, serve a message like Search in this area etc. Google maps behave something like this manner.

3. Serve the latest ajax request and abort others:

This can be done, by pushing the requests in a queue/order and send the last one to get the response. like if you are catering it via ajax, so some code like below code, if I call getFoo for 10 times, the last one will be fired

var ajax = null;
var getFoo = function() {
    if(ajax) ajax.abort();
    ajax= $.ajax({});
};

Upvotes: 3

Related Questions