promiseUtils

AMD: require(["esri/core/promiseUtils"], (promiseUtils) => { /* code goes here */ });
ESM: import * as promiseUtils from "@arcgis/core/core/promiseUtils.js";
Object: esri/core/promiseUtils
Since: ArcGIS Maps SDK for JavaScript 4.2

Various utilities and convenience functions for working with promises.

Method Overview

Name Return Type Summary Object

Creates a special error object which is used to signal aborted requests in promise chains.

promiseUtils

A utility for ensuring an input function is not simultaneously invoked more than once at a time.

promiseUtils

Convenience utility method to wait for a number of promises to either resolve or reject.

promiseUtils

A convenience utility method for filtering an array of values using an asynchronous predicate function.

promiseUtils

Check if the provided error object is the special kind of error with which promises are rejected when they are aborted.

promiseUtils

Method Details

createAbortError

Method
createAbortError(){Error}

Creates a special error object which is used to signal aborted requests in promise chains. Promises that are rejected due to abort signals should reject with this kind of error.

Returns
Type Description
Error A special error object that signals an aborted request.
Example
// Request multiple files and return results in an array
function requestMultiple(urls, abortSignal) {
  // Fire off requests
  let promises = urls.map(url => request(url, { signal: abortSignal });

  // Wait until all requests have either resolved or rejected
  promiseUtils.eachAlways(urls)
    .then(results => {
      if (abortSignal && abortSignal.aborted) {
        // If the user has triggered the abortSignal, all requests will react and reject. eachAlways resolves with
        // an array that contains the reject error for each request. Instead of returning this array as a result, we
        // should reject the promise returned to the user with an abort error.
        throw promiseUtils.createAbortError();
      }
      return results;
  });
}

debounce

Method
debounce(callback){Function}static
Since: ArcGIS Maps SDK for JavaScript 4.12 promiseUtils since 4.2, debounce added at 4.12.

A utility for ensuring an input function is not simultaneously invoked more than once at a time. This is useful for highly interactive applications such as those that execute statistic queries on mouse-move or mouse-drag events. Rather than execute the query for each such event, you can "debounce", or cancel the function execution, until the previous execution of the same function call finishes. This improves the performance and user experience of such applications.

Parameter
callback Function

A function to prevent executing during the execution of a previous call to the same function. This is typically a function that may be called on mouse-move or mouse-drag events.

Returns
Type Description
Function A function with the same signature as the callback.
Example
// Queries a layer for the count of features that intersect a
// 1 km buffer of the pointer location. The debounce() method
// prevents the updateStatistics function from executing before
// a previous invocation of the same function finishes.
const updateStatistics = promiseUtils.debounce(function (geometry) {
  return layerView.queryFeatures({
    geometry,
    distance: 1,
    units: "kilometers",
    outStatistics: [{
      onStatisticField: "*",
      outStatisticFieldName: "feature_count",
      statisticType: "count"
    }]
  }).then(function(featureSet) {
    console.log(`Feature Count: ${featureSet.features[0].attributes["feature_count"]}`);
  });
});

view.on("drag", (event) => updateStatistics(view.toMap(event)));

eachAlways

Method
eachAlways(promises){Promise}

Convenience utility method to wait for a number of promises to either resolve or reject. The resulting promise resolves to an array of result objects containing the promise and either a value if the promise resolved, or an error if the promise rejected. This is similar to the native Promise.allSettled method with the additional feature of taking an object parameter.

Parameter
promises Promise[]|Object

Array of promises, or object where each property is a promise.

Returns
Type Description
Promise If called with an array of promises, resolves to an array of result objects containing the original promise and either a value (if the promise resolved) or an error (if the promise rejected). If called with an object where each property is a promise, then resolves to an object with the same properties where each property value is a result object.
Example
const controller = new AbortController();

// Query for the number of features from
// multiple feature layers
function queryLayerFeatureCount(whereClauses) {
  // pass each whereClause item into callback function
  return promiseUtils.eachAlways(whereClauses.map(function (whereClause) {
    return layer.queryFeatureCount(whereClause, {
      signal: controller.signal
    });
  }));
}

queryLayerFeatureCount(whereClauses).then(function(eachAlwaysResults) {
   eachAlwaysResults.forEach(function(result) {
     // If a Promise was rejected, you can check for the rejected error
     if (result.error) {
       console.log("There was an error in your query.", result.error);
     }
     // The results of the Promise are returned in the value property
     else {
       console.log("The number of features are: " + result.value);
     }
   });
});

filter

Method
filter(input, predicate){Promise}

A convenience utility method for filtering an array of values using an asynchronous predicate function.

Parameters
input Array

The array of input values to filter.

A predicate function returning a promise. Only array entries for which the returned promise contains true are kept.

Returns
Type Description
Promise A promise containing an array of values that passed the predicate check.

isAbortError

Method
isAbortError(error){Boolean}

Check if the provided error object is the special kind of error with which promises are rejected when they are aborted.

Parameter
error Error

The error object to test.

Returns
Type Description
Boolean true if the error is an abort error, false otherwise.
Example
// This function fetches a document via HTTP and logs its content to the console once available
function logHTTPDocumentToConsole(url, abortSignal) {
  // Pass the abort signal into `request` to make it cancelable
  request(url, { signal: abortSignal })
    .then((response) => {
      console.log(response.data);
    })
    .catch((error) => {
      if (!promiseUtils.isAbortError(error)) {
        // Only log request failures and ignore cancellations
        console.error("request error", error);
      }
    });
}

let controller = new AbortController();

let url = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer";
logHTTPDocumentToConsole(url, controller.signal);

// Cancel the request
controller.abort();

Type Definitions

EachAlwaysResult

Type Definition
EachAlwaysResult Object

The result object for a promise passed to promiseUtils.eachAlways.

Properties
promise Promise

The promise that has been fulfilled.

value *
optional

The value with which the promise resolved. Defined only if the promise resolved.

error *
optional

The error with which the promise rejected. Defined only if the promise rejected.

Executor

Type Definition
Executor(resolve, reject)

A function that defines how a promise created in create() is resolved and rejected.

Parameters
resolve ResolveCallback

A function that will fulfill the promise.

A function that will handle the rejection of the promise.

FilterPredicateCallback

Type Definition
FilterPredicateCallback(value, index){Promise}

Callback to be called for each entry of an array to be filtered.

Parameters
value *

The value of the array entry.

index Number

The index of the entry within the array.

Returns
Type Description
Promise A promise that resolves to a boolean value, indicating whether the entry should be kept in the filtered array.

RejectCallback

Type Definition
RejectCallback(error)

A function that will reject the promise created in create().

Parameter
error *
optional

The error with which the promise rejected. Defined only if the promise is rejected.

ResolveCallback

Type Definition
ResolveCallback(value)

A function that will resolve the promise created in create().

Parameter
value *|Promise<*>
optional

The value with which the promise resolved. Defined only if the promise is fulfilled.

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.