Asynchronous Functions in Expressions
Expression questions support custom asynchronous functions that you can use for time-consuming operations, such as requests to a server. In this example, you can select a country from a drop-down list. Two Expression questions use asynchronous functions to load and display the selected country's region and official name.
To implement an asynchronous function for use in expressions, follow the steps below:
Declare an asynchronous JavaScript function.
This function accepts all arguments in one array-like object. You can pass as many arguments as needed when you call the function from an expression. To return the function's result, pass it to thethis.returnResult
function.function asyncFunc(params) { const arg1 = params[0]; const arg2 = params[1]; // ... setTimeout(() => { // Return the function result via the callback this.returnResult(yourValue); }, 100); }
Register your function in
FunctionFactory
.
Call a staticregister()
method on theFunctionFactory.Instance
object. This method accepts a function name that you want to use in expressions, the function itself, and atrue
flag that indicates an asynchronous function.import { FunctionFactory } from "survey-core"; FunctionFactory.Instance.register("asyncFunc", asyncFunc, true);
Use your function in an Expression question.
Specify the question'sexpression
property.const surveyJson = { "elements": [{ "type": "expression", "name": "asyncExpression", // ... "expression": "asyncFunc({question1}, {question2})" }, { // ... }] };
(Optional) Hide an Expression question until it has a value.
You may want to hide your Expression question until its asynchronous function has executed. To do it, set thevisibleIf
property to a Boolean expression that uses thenotempty
function. Refer to the following help topic for more information: Conditional Visibility.const surveyJson = { "elements": [{ "type": "expression", "name": "asyncExpression", // ... "expression": "asyncFunc({question1}, {question2})", "visibleIf": "{asyncExpression} notempty" }, { // ... }] };