RunAsync

Description

A function that returns a Future object. For more information, see Asynchronous programming in ColdFusion.

Returns

A Future object.

Syntax

RunAsync()

RunAsync(UDFMethod function)

RunAsync(UDFMethod function, long timeOut)

History

New in ColdFusion (2018 release).

Parameters

Parameter

Required/Optional

Description

function

Optional

Closure function that returns a Future object, which holds the result of execution, status, and so on.

timeOut

Optional

Timeout in milliseconds.

Example 1

<cfscript>
             //To run a function asynchronously and get the result
             future = runAsync(function(){
                           return "Hello World!";
                      });
             result = future;
             writeOutput(result.get());
</cfscript>

Example 2

In this example, you'll see how we chain two methods, display a result.

<cfscript>

// Define a function to fetch the response from a URL
function fetchResponseFromURL(url) {
    result = "";
    httpService = new http(method = "GET", charset = "utf-8", url = url);
    httpService.addParam(name = "q", type = "url", value = "cfml");
    result = httpService.send().getPrefix();
    writeDump(result);
    return result;
}

// once the response is fetched, do the processing (here we just deserialize the json)
future = runAsync(function(){
    return fetchResponseFromUrl("http://date.jsontest.com/");
    }).then( function(input){
        return deserializeJson(input.FileContent)
    });
    result = future.get()
    writedump(result);
</cfscript>

Output

Example 3

In this example, you'll see a non-blocking scenario where we've defined asynchronous functions to send email and SMS.

<cfscript>

// Define an asynchronous function to send an email
function sendEmailAsync(toAddress, subject, body) {
    cfmail(to=toAddress, subject=subject, body=body, type="html");
}

// Define an asynchronous function to send an SMS
function sendSmsAsync(phoneNumber, message) {
    // Replace the following line with your actual SMS sending logic
    // Example: sendSmsFunction(phoneNumber, message);
}

// List of recipients with real-world-like data
recipients = [
    { email: "recipient1@example.com", phone: "1234567890", subject: "Subject 1", body: "Body 1" },
    { email: "recipient2@example.com", phone: "0987654321", subject: "Subject 2", body: "Body 2" },
    { email: "recipient3@example.com", phone: "5555555555", subject: "Subject 3", body: "Body 3" },
    { email: "recipient4@example.com", phone: "6666666666", subject: "Subject 4", body: "Body 4" },
    { email: "recipient5@example.com", phone: "7777777777", subject: "Subject 5", body: "Body 5" },
    { email: "recipient6@example.com", phone: "8888888888", subject: "Subject 6", body: "Body 6" },
    { email: "recipient7@example.com", phone: "9999999999", subject: "Subject 7", body: "Body 7" },
    { email: "recipient8@example.com", phone: "1010101010", subject: "Subject 8", body: "Body 8" },
    { email: "recipient9@example.com", phone: "2020202020", subject: "Subject 9", body: "Body 9" },
    { email: "recipient10@example.com", phone: "3030303030", subject: "Subject 10", body: "Body 10" }
];

// Start the email sending process asynchronously for each recipient
for (var i = 1; i <= arrayLen(recipients); i++) {
    var recipient = recipients[i];
    runAsync(function() {
        sendEmailAsync(recipient.email, recipient.subject, recipient.body);
    });
}

// Start the SMS sending process asynchronously for each recipient
for (var i = 1; i <= arrayLen(recipients); i++) {
    var recipient = recipients[i];
    runAsync(function() {
        sendSmsAsync(recipient.phone, "SMS message content");
    });
}

// The following code will execute immediately without waiting for the email and SMS sending processes to complete
writeOutput("In main thread...<br>");

</cfscript>

Example 4

In this example, you'll learn to use parallel processing using runAsync, where you'll generate the first 100000 Fibonacci numbers, and also perform a matrix multiplication.

<cfscript>
             //Task 1
             fibonacciTask = runAsync(function(){
                    // Generate first 10000000 Fibonacci numbers
                   fib = [0, 1];
                    for (var i = 3; i < 10000000; i++) {
                        fib[i] = fib[i-1] + fib[i-2];
                    }
                    return fib;
              });
              // Task 2
             matrixMultiplicationTask = runAsync(function(){

                    var matrix1 = [];
                    var matrix2 = [];
                    var result = [];

                    // Generate random matrices (for simplicity, let's assume values are between 1 and 10)
                    for (var i = 1; i <= 200; i++) {
                        matrix1[i] = [];
                        matrix2[i] = [];
                        result[i] = [];
                        for (var j = 1; j <= 200; j++) {
                            matrix1[i][j] = randRange(1, 10);
                            matrix2[i][j] = randRange(1, 10);
                        }
                    }

                    // Multiply matrices
                    for (var i = 1; i <= 200; i++) {
                        for (var j = 1; j <= 200; j++) {
                            result[i][j] = 0;
                            for (var k = 1; k <= 200; k++) {
                                result[i][j] = result[i][j] + matrix1[i][k] * matrix2[k][j];
                            }
                        }
                    }
                    return result;
              });
              //Task 3
             sleepingTask = runAsync(function(){
                    sleep(9000);
              });
             writedump(fibonacciTask.get());
             writedump(matrixMultiplicationTask.get());
             writedump(sleepingTask.get());

</cfscript>

Example 5

In this example, you'll learn to use parallel processing using runAsync, where you'll check if a number is prime, calculate the sum of the prime numbers, and start multiple asynchronous tasks to calculate the sum of prime numbers in parallel.

<cfscript>

// Function to check if a number is prime
function isPrime(num) {
    if (num <= 1) return false;
    if (num <= 3) return true;

    if (num MOD 2 EQ 0 OR num MOD 3 EQ 0) return false;

    var i = 5;
    while (i * i <= num) {
        if (num MOD i EQ 0 OR num MOD (i + 2) EQ 0) return false;
        i = i + 6;
    }

    return true;
}

// Function to calculate the sum of prime numbers
function calculatePrimeSum(start, end) {
    var sum = 0;
    for (var i = start; i <= end; i++) {
        if (isPrime(i)) {
            sum = sum + i;
        }
    }
    return sum;
}

// Define the range for prime number calculation
startRange = 1;
endRange = 10000;

// Start multiple asynchronous tasks to calculate the sum of prime numbers in parallel
task1Id = runAsync(function() {
    result1 = calculatePrimeSum(startRange, 2500);
    return result1;
});

task2Id = runAsync(function() {
    result2 = calculatePrimeSum(2501, 5000);
    return result2;
});

task3Id = runAsync(function() {
    result3 = calculatePrimeSum(5001, 7500);
    return result3;
});

task4Id = runAsync(function() {
    result4 = calculatePrimeSum(7501, endRange);
    return result4;
});

// The following code will execute immediately without waiting for the async tasks to complete
    writeOutput("In main thread...<br>...<br>");
    writeDump(var=task1Id.get(), label="Task 1 ID");
    writeDump(var=task2Id.get(), label="Task 2 ID");
    writeDump(var=task3Id.get(), label="Task 3 ID");
    writeDump(var=task4Id.get(), label="Task 4 ID");
</cfscript>

Output

In main thread...
...
420812 1127324 1749901 2438359

 Adobe

Get help faster and easier

New user?

Adobe MAX 2024

Adobe MAX
The Creativity Conference

Oct 14–16 Miami Beach and online

Adobe MAX

The Creativity Conference

Oct 14–16 Miami Beach and online

Adobe MAX 2024

Adobe MAX
The Creativity Conference

Oct 14–16 Miami Beach and online

Adobe MAX

The Creativity Conference

Oct 14–16 Miami Beach and online