Skip to content

Commit 0f764b6

Browse files
Document async/await and Promise handling in Code Interpreter
Adds documentation for automatic Promise resolution in JavaScript and TypeScript contexts. The Code Interpreter now properly awaits Promise results, allowing async/await patterns to work correctly. Includes examples for: - Async IIFE patterns - Direct Promise.resolve usage - Nested async operations - Async error handling with Promise.reject References cloudflare/sandbox-sdk#246
1 parent ad91c85 commit 0f764b6

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

src/content/docs/sandbox/api/interpreter.mdx

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,45 @@ console.log(result.results[0].text); // "15"
9090
</TypeScriptExample>
9191
:::
9292

93+
**Async/await and Promise handling (JavaScript and TypeScript)**:
94+
95+
The Code Interpreter automatically awaits Promise results in JavaScript and TypeScript contexts, allowing you to work with async code naturally.
96+
97+
<TypeScriptExample>
98+
```
99+
const ctx = await sandbox.createCodeContext({ language: 'javascript' });
100+
101+
// Async IIFE
102+
const result1 = await sandbox.runCode(`
103+
(async () => {
104+
const value = await Promise.resolve(42);
105+
return { result: value * 2 };
106+
})()
107+
`, { context: ctx });
108+
109+
console.log(result1.results[0].json); // { result: 84 }
110+
111+
// Direct Promise.resolve
112+
const result2 = await sandbox.runCode(
113+
'Promise.resolve({ status: "success" })',
114+
{ context: ctx }
115+
);
116+
117+
console.log(result2.results[0].json); // { status: "success" }
118+
119+
// Nested async operations
120+
const result3 = await sandbox.runCode(`
121+
(async () => {
122+
const a = await Promise.resolve(10);
123+
const b = await Promise.resolve(20);
124+
return { sum: a + b };
125+
})()
126+
`, { context: ctx });
127+
128+
console.log(result3.results[0].json); // { sum: 30 }
129+
```
130+
</TypeScriptExample>
131+
93132
**Error handling**:
94133

95134
<TypeScriptExample>
@@ -104,6 +143,21 @@ if (result.error) {
104143
```
105144
</TypeScriptExample>
106145

146+
**Async error handling**:
147+
148+
<TypeScriptExample>
149+
```
150+
const result = await sandbox.runCode(
151+
'Promise.reject(new Error("Async error"))',
152+
{ language: 'javascript' }
153+
);
154+
155+
if (result.error) {
156+
console.error(result.error.message); // "Async error"
157+
}
158+
```
159+
</TypeScriptExample>
160+
107161
### `listCodeContexts()`
108162

109163
List all active code execution contexts.

0 commit comments

Comments
 (0)