Question: Is it possible to use async await in rules?
Answer:
Yes, you can use async/await in a rule.
You can use it in a function that you define, or you can use it directly in the top-level function.
In a function within the rule:
In this example, we create a getEcho
function that we can define as async.
function (user, context, callback) {
const axios = require("axios");
const getEcho = async () => {
try {
const resultA = await axios.get("https://postman-echo.com/get?foo1=bar1");
console.log(resultA.data);
const resultB = await axios.get(`https://postman-echo.com/get?foo2=${resultA.data.args.foo1}`);
console.log(resultB.data);
} catch (error) {
console.error(error);
throw error;
}
};
getEcho()
.then(() => callback(null, user, context))
.catch((e) => callback(new Error("Error echoing " + e.msg)));
}
In the top level function:
In this example, we define the top-level function as async.
async function (user, context, callback) {
const axios = require("axios");
try {
const resultA = await axios.get("https://postman-echo.com/get?foo1=bar1");
console.log(resultA.data);
const resultB = await axios.get(`https://postman-echo.com/get?foo2=${resultA.data.args.foo1}`);
console.log(resultB.data);
} catch (error) {
callback(new Error("Error echoing " + error.msg));
}
return callback(null, user, context);
}
Supporting Documentation:
Community Topic: Related Topic