Skip to content

Commit 68c4a9a

Browse files
Add async/await examples to code execution guide
Adds practical examples of async JavaScript/TypeScript execution to the how-to guide, demonstrating data processing workflows with Promises. References cloudflare/sandbox-sdk#246
1 parent 0f764b6 commit 68c4a9a

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/content/docs/sandbox/guides/code-execution.mdx

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,37 @@ console.log(result.output); // "Mean: 3.0"
107107
Context state is lost if the container restarts due to inactivity. For critical data, store results outside the sandbox or design your code to reinitialize as needed.
108108
:::
109109

110+
### Async JavaScript and TypeScript
111+
112+
The Code Interpreter automatically awaits Promise results in JavaScript and TypeScript contexts:
113+
114+
<TypeScriptExample>
115+
```
116+
const context = await sandbox.createCodeContext({
117+
language: 'javascript'
118+
});
119+
120+
// Async functions are automatically awaited
121+
const result1 = await sandbox.runCode(`
122+
(async () => {
123+
const response = await Promise.resolve({ data: [1, 2, 3, 4, 5] });
124+
const sum = response.data.reduce((a, b) => a + b, 0);
125+
return { sum, count: response.data.length };
126+
})()
127+
`, { context: context.id });
128+
129+
console.log(result1.results[0].json); // { sum: 15, count: 5 }
130+
131+
// Promise.resolve works directly
132+
const result2 = await sandbox.runCode(
133+
'Promise.resolve({ status: "complete", timestamp: Date.now() })',
134+
{ context: context.id }
135+
);
136+
137+
console.log(result2.results[0].json); // { status: "complete", timestamp: ... }
138+
```
139+
</TypeScriptExample>
140+
110141
## Handle rich outputs
111142

112143
The code interpreter returns multiple output formats:

0 commit comments

Comments
 (0)