7

How can I write a Promise where the response is coming from an iron-ajax.

<iron-ajax id="listItems" method="GET" content-type="application/json" handle-as="json" last-response="{{items}}" on-error="handleErrorResponse"></iron-ajax>

this.data =  {
    get: function(sort, page, pageSize) {
            return new Promise(function(resolve, reject) {
                // Execute iron-ajax.
                //...
                // resolve(iron-ajax's response);
            });
        }
    }
};
His
  • 5,891
  • 15
  • 61
  • 82
  • you may want to `return new Promise ...` for a start, otherwise the promise stuff is pointless – Jaromanda X Apr 03 '17 at 02:59
  • @JaromandaX, yep, that's done. Are you able to help? – His Apr 03 '17 at 03:01
  • No - because I can't see why you'd need a Promise at all - given the iron-ajax documentation - some more context for your issue (more code) may help – Jaromanda X Apr 03 '17 at 03:03
  • @JaromandaX, I'm integrating with http://david-mulder.github.io/paper-datatable/components/paper-datatable/docs/docs.html?getting-started-with-data-table-cards, where I need to implement the interface returning a Promise and the items to be displayed are obtained from an ajax request. – His Apr 03 '17 at 03:11

1 Answers1

8

You're looking for listItem.generateRequest(), since that returns iron-ajax's accompanying iron-request object, which in turn provides a promise, named request.completes.

https://www.webcomponents.org/element/PolymerElements/iron-ajax/iron-ajax#method-generateRequest

https://www.webcomponents.org/element/PolymerElements/iron-ajax/iron-request#property-completes

I modified your code sample below:

<iron-ajax id="listItems" method="GET" content-type="application/json" handle-as="json" last-response="{{items}}" on-error="handleErrorResponse"></iron-ajax>

this.data =  {
    get: function(sort, page, pageSize) {
            return this.$.listItems.generateRequest().completes;
        }
    }
};

Inspired by the more complex example at https://stackoverflow.com/a/37995462/2795627. Kudos to @akivajgordon.

Community
  • 1
  • 1
craPkit
  • 615
  • 1
  • 7
  • 20