Set Property of a Class with Return Value From async Request

403
3
Jump to solution
03-11-2020 08:19 AM
BenRomlein
Occasional Contributor

Using JS API 4.14, I have a custom Accessor class serving as the view model to a UI widget. I want to query a server to get a list of service groups available, and render that list in the UI. I have a property in my class that I want to set to the return value of the request:

  @property()
  layerGroupsstring = null;

I'm trying to use the code below to make the request and set the value, but this does not work. No console error, but the value of layerGroups remains null. I assume because request is an async operation, so it doesn't have access to the return value at the right time. 

> widget.viewModel.layerGroups
> null

    const getLayerGroups = request("https://my.server/arcgis/rest/", {query: {f: "json"}, responseType: "json"}).then(response => this.set(this.layerGroupsresponse.data.folders));

Normally, I'd just nest the rest of my code in the callback and I'd have easy access to the returned value. But the Accessor class/widget code is more compartmentalized, and I'm not sure how and where to implement things.

How can I make this work? Do I need to put my async operations in a different lifecycle section of my class (I've only tried them in the constructor)? Is this a scoping issue? Appreciate any advice you have. Thanks!

EDIT: request here is the esri/request:

import request = require("esri/request");
0 Kudos
1 Solution

Accepted Solutions
BenRomlein
Occasional Contributor

In case anyone needs this, here's how I got it to work:

 private async _getLayerGroups() {
    let layerGroups = await request("https://gis.server.com/arcgis/rest/", {query: {f: "json"}, responseType: "json"}).then(response => response.data.folders);

You need to nest the request call in an async function and use await to make sure the value is available. This code returns an array, so I had to change the property type accordingly also.

View solution in original post

0 Kudos
3 Replies
BenRomlein
Occasional Contributor

bump...

Still looking for advice on this is anyone has employed a similar work-flow.

0 Kudos
BenRomlein
Occasional Contributor

bump.
Anyone have anything on this?

0 Kudos
BenRomlein
Occasional Contributor

In case anyone needs this, here's how I got it to work:

 private async _getLayerGroups() {
    let layerGroups = await request("https://gis.server.com/arcgis/rest/", {query: {f: "json"}, responseType: "json"}).then(response => response.data.folders);

You need to nest the request call in an async function and use await to make sure the value is available. This code returns an array, so I had to change the property type accordingly also.

0 Kudos