This example demonstrates a simple for-each
(or: for ... of
) statement. It converts an array of numbers to a single string. in order to ensure there is no leading ,
a local variable is used to treat the first element in the array differently. This function returns 1, 2, 3.
.
Open in playground
export const main = asl.deploy.asStateMachine(async () => {
const arr = [1, 2, 3];
let result = "";
// use a for loop to append all numbers to a single string
for (const item of arr) {
if (result === "") {
//first element should not be prefixed with a comma
result = asl.convert.numberToString(item);
} else {
result = `${result}, ${item}`;
}
}
return result;
});
This example demonstrates a break
statement within a for-each
statement. The break statements exists the loop after number 2
was added to the list. this function returns 1, 2
.
Open in playground
export const main = asl.deploy.asStateMachine(async () => {
const arr = [1, 2, 3];
let result = "";
// use a for loop to append all numbers to a single string
for (const item of arr) {
if (result === "") {
//first element should not be prefixed with a comma
result = asl.convert.numberToString(item);
} else {
result = `${result}, ${item}`;
}
if (item === 2) {
break; // this break will prevent 3 from being added to the string
}
}
return result;
});
This example demonstrates a continue
statement within a for-each
statement. The continue
statements prevents number 2
from being added to the list. this function returns 1, 3
.
Open in playground
export const main = asl.deploy.asStateMachine(async () => {
const arr = [1, 2, 3];
let result = "";
// use a for loop to append all numbers to a single string
for (const item of arr) {
if (item === 2) {
continue; // this break will prevent 2 from being added to the string
}
if (result === "") {
//first element should not be prefixed with a comma
result = asl.convert.numberToString(item);
} else {
result = `${result}, ${item}`;
}
}
return result; //returns "1, 3"
});
This example demonstrates a return
statement within a for-each
statement. The return
prevents the loop from processing, and the function returns found 2!
.
Open in playground
export const main = asl.deploy.asStateMachine(async () => {
const arr = [1, 2, 3];
for (const item of arr) {
if (item === 2) {
return `found ${item}!`; //returns "found 2!"
}
}
throw new Error("should not get here");
});
export const main = asl.deploy.asStateMachine(async () => {
const numbers = [0, 1, 2, 3];
const letters = ["a", "b", "c", "d"];
const global = "prefix";
const outer = { middle: { inner: 3 } };
let result = ``;
for (const number of numbers) {
for (const letter of letters) {
const combined = { number, letter, global, inner: outer.middle.inner };
result = `${result}, ${asl.states.jsonToString(combined)}`;
}
}
return result;
});
export const main = asl.deploy.asStateMachine(async () => {
const numbers = [0, 1, 2, 3];
for (const _number of numbers) {
}
return "ok";
});