Code Actions Best Practices
Cloud code actions provide an easy way to make your bot truly dynamic. These are some of the best practices we like to share.
Use async
Cloud code is a single JavaScript (ES6) function. We advise everyone to write async functions.
async payload => {
// your code there
}
Before, you had to write nested code with callbacks. Using async allows you to write better readable pieces of code.
// The old way
(function(payload) => {
request('https://awesome.org/1')
.then(response1 => {
// Do something with the first response
request('https://awesome.org/2')
.then(response2 => {
// Do something with the second response
})
.catch(err => {
console.error('Error', err)
})
})
.catch(err => {
console.error('Error', err)
})
})
Async functions allow you to write simple code like:
// The old way
async payload => {
try {
const response1 = await request('https://awesome.org/1')
// Do something with the first response
const response2 = await request('https://awesome.org/2')
// Do something with the second response
} catch(err) {
console.error('Error', err)
}
}
Keep it short and simple
It's better to break up different actions.
Check if a parameter exists
Optional parameters can be empty! Always check to see if they are present or not. Since a parameter are always lists (arrays) you can use something like:
if(Array.isArray(payload.params.myparam)) {
// We have a param
}
Use return instead of reply
The reply()
method is only intended for callback functions.
If you can try to use the await
calls and return messages instead of using the reply method.
Use triggers instead of messages
Using triggers as much as possible for static content allows you to keep all content inside the flows editor. This makes it far easier to built cross language code and maintain.