Polymer iron-ajax and asynchronous requests (sort of synchronization and response processing)

I am looking for a tried and true way to handle asynchronous calls to API endpoints that return JSON (using the latest modification to the iron-ajax element). These API calls rely on etag compliance, so it is important that etag sends compliance on the server. I have this part of the job, except in certain circumstances where quick-sequence API calls can trigger an out-of-order response (and therefore can get etag synchronization). There are also several API endpoints (i.e., Different URLs). Thus, sometimes, if quick sequence calls using different endpoints are initiated using the iron-ajax element, this can cause problems for the response handler function, because the response handler is currently checking the ajax element's URL to knowhow to handle the answer correctly. Therefore, if the second call rewrites the URL of the ajax component before receiving a response to the 1st call, when the 1st call is returned, responseHandler does not handle it accordingly. Perhaps there is a much better and reliable way to check which call has returned?

I know that I am not the first person to come across this scenario, so I wonder if anyone can show me an enlightened path? I think that there is a simple strategy to solve this problem, perhaps queuing calls, etc., but I'm not sure if the iron-ayax has something built-in that could help in this regard.

An example with some sample code would be absolutely awesome!

+1
source share
2 answers

If you depend on multiple API endpoints, I will have a separate element iron-ajaxfor each of them so that they do not stomp with each other if the URLs change (by data binding or something else):

<iron-ajax id="cats" url="https://api.example.com/cats" handle-as="json"></iron-ajax>
<iron-ajax id="dogs" url="https://api.example.com/dogs" handle-as="json"></iron-ajax>

Promise.all(), :

<script>
    Polymer({
        is: 'my-element',

        ...,

        fetchPets: function () {
            var catsRequest = this.$.cats.generateRequest();
            var dogsRequest = this.$.dogs.generateRequest();

            Promise.all([catsRequest.completes, dogsRequest.completes])
                .then(function (requests) {
                    var cats = requests[0].response;
                    var dogs = requests[1].response;

                    // do whatever you want from here...
                    alert(cats.concat(dogs));
                });
        }
    })
</script>
+6

-, - - .

, , , , , , .

http://www.html5rocks.com/en/tutorials/es6/promises/

-: http://www.html5rocks.com/en/tutorials/es6/promises/async-best-example.html

, Promise.all( ). then (...), .

iron-ajax, , iron, . , .

, , , Promises, Promise.all .then .

0

Source: https://habr.com/ru/post/1016262/


All Articles