Loadable: Dropping the Pretense of Immediate-Enough

327
1
04-08-2021 03:33 PM
ZianChoy
Occasional Contributor

One of the major changes with the 4.* JS API has been the use of the asynchronous loading as much as possible (https://developers.arcgis.com/javascript/latest/programming-patterns/#async-data and https://community.esri.com/t5/developers-blog/the-quot-loadable-quot-power-of-the-arcgis-runtime-sdk...).

For example, in https://developers.arcgis.com/javascript/latest/sample-code/sandbox/index.html?sample=views-composit..., the code looks like this:

var layer = new FeatureLayer();

var map = new Map(layer);

var mainView = new MapView(map);

//pulled out the new Legend to make it clearer

var l = new Legend({
view: mainView
});

mainView.ui.add(l),"bottom-right");

Would it be better for the sample to wait for each prerequisite to finish loading like this?

var layer = new FeatureLayer("URL pointing to a slow AGS server");

//Wait for the slow server to respond...

await layer.load();

var map = new Map(layer);

var mainView = new MapView(map);

//Wait for the MapView to finish getting what it wants from the slow layer(s)

for (const lv in mainView.allLayerViews)

{

await mainView.whenLayerView(lv);

}

//Now that the LayerView and MapView know exactly how to show everything (e.g. renderer symbols and the corresponding DOM nodes) we can add the layers to the legend with the right symbology and labels.

var l = new Legend({
view: mainView
});

mainView.ui.add(l),"bottom-right");

Something doesn't feel quite right because in the ESRI Dev Summit 2021 session about customizing widgets (ArcGIS API for Javascript: Customizing Widgets at 2 PM), I don't recall the presenter having to put "await" all over his code before being able to mess with the widget's HTML.

Although I asked this question during the ESRI Dev Summit 2021 "ArcGIS API for Javascript: Everything You Wanted to Know But Were Afraid to Ask" session, I know it's over so if no one sees this, I'll re-post it elsewhere in a few days.

0 Kudos
1 Reply
jcfranco
New Contributor

Hi Zian.

If you're asking whether the await version of the snippet is better than the other one, it really depends on your use case. For example, if you have some code that needs for the layer or something else to be ready before using it, awaiting on these different parts makes sense as it allows you to write your code as if it were synchronous without callbacks or chaining then promise calls (even though it is still executing asynchronously). If your code only needs to show the legend with the corresponding data, not using await is also valid as the widget will update as soon as resources are available.

Hope this helps and happy coding!

0 Kudos