Async & Await
This document is a quick introduction to using the async and await syntactic sugar in CloudCode tasks and in TypeScript apps.
Start with this interactive introduction to async & await if you are not familiar with the syntax at all.
Introduction to async and await usage
In JourneyApps many operations are asynchronous. We use async & await to handle this.
In CloudCode, your main run function should always be async:
export async function run() {
// Code here
}Generally, database operations that query the backend are asynchronous, and needs await:
export async function run() {
var user = await DB.user.first();
console.log('name:', user.name);
// This doesn't hit the database yet, so does not need `await`
var assignment = DB.assignment.create();
assignment.user(user);
await assignment.save();
}Fetch calls are also asynchronous and therefore require an await:
If you define an async function, you also need to await on its response:
Notable async operations:
Getting belongs-to relationships are also async. If a chain of belongs-to lookups are performed, each one requires an await. For readable code, it is recommended to do each belongs-to lookup on a separate line. For example:
for loops require specific attention: someArray.forEach does not wait for async functions to complete, so it is recommend to use a for...of loop instead:
For example:
Last updated