In JourneyApps many operations are asynchronous. We use async & await to handle this.
In CloudCode, your main run function should always be async:
exportasyncfunctionrun() {// Code here}
Generally, database operations that query the backend are asynchronous, and needs await:
exportasyncfunctionrun() {var user =awaitDB.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);awaitassignment.save();}
Fetch calls are also asynchronous and therefore require an await:
exportasyncfunctionrun() {var response =awaitfetch("http://api.open-notify.org/iss-now.json");if(!response.ok) {thrownewError('Request failed: '+response.statusText); }var body =awaitresponse.json();returnbody.iss_position;}
If you define an async function, you also need to await on its response:
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:
// Works, but not readablelet clientName = (await (awaituser.assignment()).client()).name;// More readablelet assignment =awaituser.assignment();let client =awaitassignment.client();let clientName =client.name;
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:
var objects =awaitDB.myobject.all().toArray();for(let object of objects) {// ...}
For example:
exportasyncfunctionrun() {// Task to recalculate the totals for all invoicesvar invoices =awaitDB.invoices.all().toArray();for(let invoice of invoices) {var line_items =awaitinvoice.line_items.toArray();var total =0;for(let line_item of line_items) {var product =awaitline_item.product();var price =product.price *line_item.quantity; total += price; }invoice.total = total;awaitinvoice.save(); }}