Introduction
In this blog post, we will show you how to call an asynchronous Power Automate flow with JavaScript. This is useful if you want to trigger a flow from a web application or a script, and you want to continue with other tasks while the flow is running in the background.
We will start by explaining what asynchronous flows are and why they are useful. Then, we look at how to create an asynchronous Power Automate flow using the “When a HTTP request is received” connector. This connector allows you to trigger flows by making HTTP requests. Next, we will look at how to call asynchronous flows using JavaScript.
By the end of this post, you will know how to call asynchronous Power Automate flows from JavaScript, and you will be able to use this knowledge to automate tasks and processes in your applications.
Table of Content
- What is an Asynchronous Power Automate Flow
- How to Create an Asynchronous Power Automate Flow
- How to Call Asynchronous Power Automate Flow with JavaScript
Prerequisites
- You will need a Microsoft Power Automate account. If you don’t have one, you can sign up for a free trial or purchase a subscription.
- Familiar with Power Automate
- Basic understanding of JavaScript, including how to use functions, variables, and conditional statements.
What is an Asynchronous Power Automate Flow
An asynchronous Power Automate flow is a type of flow that runs automatically in the background. It does not require user intervention. Furthermore, these flows can be triggered by events or schedules, and they can continue running even after the user who started them closes the application or logs out.
Asynchronous flows are useful when you want to automate tasks or processes that may take a long time to complete, or when you want to trigger a flow from a web application or a script, and you want to continue with other tasks while the flow is running in the background.
There are several different states that an asynchronous flow can be in, depending on its current status. Here are the most common states:
- Pending: This is the initial state of a promise when it has not yet been fulfilled or rejected.
- Fulfilled: This state indicates that the promise has been completed successfully and a value is available.
- Rejected: This state indicates that the promise has failed and an error is available.
- Settled: This state indicates that the promise has either been fulfilled or rejected and is no longer pending.
- Canceled: Some implementations of promises may support a “canceled” state, which indicates that the promise has been abandoned and will not be fulfilled or rejected.
In the next part, we look at how we can create an asynchronous Power Automate flow.
How to Create an Asynchronous Power Automate Flow
Asynchronous flows are a type of Power Automate flow that allows you to execute long-running processes in the background, without having to wait for the process to complete before continuing. In this section, we look at how we can create a simple asynchronous Power Automate that will output “Hello [Name]”, where you can send the name in the payload from the JavaScript.
To create an asynchronous Power Automate flow, you can follow these steps:
Step 1: Sign in to the Power Automate portal and click on the “Create” button. If you are familiar with solutions and are adding functionality to existing apps in the Power Platform I would have created the flow inside a solution. In this example, we’re creating it outside a solution.
Step 2: Next, we want to select “Instant cloud flow” under the “Start from blank” section in the image below.
Step 3: After clicking the “Instant cloud flow” a dialog opens. When the dialog opens, you will name the flow, scroll to the bottom of the list and select the “When a HTTP request is received” trigger, and then click Create. After clicking Create, the flow will open with the selected trigger.
💡 You need to add an additional action to be allowed to save the flow.
Step 4: In this step, we will add some configurations to the trigger. Where we are adding a request body by using an example payload, and the type of method we will use to call the Power Automate flow. See the images below to see the steps to add the configurations.
After clicking the “Use sample payload to generate schema” from step 3 in the image above the dialog below will open.
In the dialog, we add the following example payload and click Done afterward.
{ "name": "William" }
After clicking Done in the dialog above a Request body JSON Schema will be generated based on the sample payload.
Step 5: After adding the configuration to the trigger, we’ll add an action that delays the flow to simulate a flow that takes a long time to complete. By using the Delay action in Power Automate. This can be found by adding a new action > Search for Delay > Select the Delay action as shown in the image below 👇
Next, we need to configure the Delay action by choosing how long we want to delay the flow. For this demo, I’ve used 30 seconds as shown in the image below.
Step 6: Lastly, the final action we are adding to the flow. Add a new action > Search for Response and add the action to the flow. Next, we’ll configure the Response settings to make it asynchronously, and add the content we want the flow to respond with. In this demo, we add the following response:
{ "result": "Hello @{triggerBody()?['name']}" }
After adding the response body > Click on the three dots (…) on the top right of the Response action and select Settings as seen in the image below.
This will open the settings view for the action as seen below > Turn on Asynchronous Response and click Done.
Step 7: In the last step, save the flow and copy the URL of the Trigger.
Step 8: Finally, the flow is complete and we can now call it from a JavaScript function. We’ll look at this in the next part.
How to Call Asynchronous Power Automate Flow with JavaScript
In this part, we look at how to call an asynchronous flow with JavaScript. This section continues with an explanation of the JavaScript code used, with and without comments. The script with comments is meant for a more explanatory walkthrough of the script and the one without comments is for the ease of copying and reusing the code.
The code below defines an async
function called checkFlowStatus
that sends a POST
request to the specified flowUrl with the provided body
. It then gets the statusUrl
from the response’s location
header, which is the URL to check the flow’s status.
The function then enters a loop that waits 3 seconds before checking the status of the flow at the statusUrl
. This loop continues until the flow’s status is no longer “Running”. When the loop exits, the function returns the flow’s final status as a string.
Finally, the code defines a flowUrl
and a body object and passes them as arguments to the checkFlowStatus
function. This function calls the Power Automate flow and allows you to test it in the developer console in the web browser for this demonstration.
You can see the commented code below where the different steps are described.
async function checkFlowStatus(flowUrl, body) { // Send a POST request to the async Power Automate flow with the provided body const response = await fetch(flowUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(body) }) // Get the location header from the response. This is the URL to check the flow's status. const statusUrl = response.headers.get('location'); // Initialize flowStatus to an empty string let flowStatus = ""; // Check the flow's status until it is no longer "Running" do { console.log("Output the flow status during the Flow run: ", flowStatus); // Wait for 3 seconds before checking the status again await new Promise(resolve => setTimeout(resolve, 3000)); // Get the flow's status let response = await fetch(statusUrl).then(response => response.json()); // Assign the flow's status to the variable flowStatus using the ternary operator. // If the response object has a truthy "properties" property and a truthy "status" property, // assign the value of response.properties.status to flowStatus. Otherwise, assign the value // of response.result to flowStatus. flowStatus = (response?.properties?.status) ? response?.properties?.status : response.result; } while (flowStatus === "Running"); // Output the flow's final status and return it in text format console.log("Flow Response", flowStatus); return flowStatus; } // Example flow URL and body let flowUrl = "ENTER FLOW URL" let body = { "name": "ENTER A NAME" } // Call the checkFlowStatus function with the flow URL and body as arguments checkFlowStatus(flowUrl, body);
In the code below you see the same code as above without comments, so it’s easy to copy and paste and reuse the function for calling an asynchronous flow.
async function checkFlowStatus(flowUrl, body) { const response = await fetch(flowUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(body) }) const statusUrl = response.headers.get('location'); let flowStatus = ""; do { console.log("Output the flow status during the Flow run: ", flowStatus); await new Promise(resolve => setTimeout(resolve, 3000)); let response = await fetch(statusUrl).then(response => response.json()); flowStatus = (response?.properties?.status) ? response?.properties?.status : response.result; } while (flowStatus === "Running"); console.log("Flow Response", flowStatus); return flowStatus; } let flowUrl = "ENTER FLOW URL" let body = { "name": "ENTER A NAME" } checkFlowStatus(flowUrl, body);
To test the code, open up the Developer console in the browser and run the code. To do this, follow the steps below, and see the GIF in the end as an example.
Step 1: We can test the flow and the JavaScript code by opening the Developer console in the browser pane we created the flow. As shown step-by-step in the image below.
Step 2: Here you will open the developer console and copy and paste the code above into it. Then, you will add the flow URL from a previous step and add a name to the name property in the payload. Press “Enter” to run the code. If the code has any syntax errors, the console will display them. Correct any errors and try running the code again.
Step 3: After you hit enter in the previous step, the code will continuously check the status URL of the flow until it is completed. You can see this process in the developer console, as shown in the image below.
When the flow completes it returns the response body from the flow and outputs it to the console as seen in the image below.
Step 4: Lastly, we look at the steps above shown as a gif. To see what it looks like.
Conclusion
In this blog post, we demonstrated how to call an asynchronous Power Automate flow from JavaScript. We explained the concept of asynchronous flows. We provide you with step-by-step instructions for creating an asynchronous Power Automate flow using the “When a HTTP request is received” trigger in Power Automate and give you JavaScript code that sends a request and listens for the flow to complete.
How you found it helpful!