fetch
ts
import {fetch} from 'mikrojs/fetch'Make HTTP requests using the familiar fetch API. Unlike the browser version, this fetch returns a Result to handle network-level failures explicitly.
Functions
fetch(input, init?)
ts
function fetch(input: string, init?: RequestInit): Promise<Result<Response, FetchError>>ts
const result = await fetch('https://api.example.com/data')
if (!result.ok) {
console.error('Fetch failed:', result.error.name)
return
}
const response = result.value
console.log('Status:', response.status)
const data = await response.json()Result vs Response
fetch returns a Result that represents whether the network request succeeded at all. The Response inside has its own .ok property that indicates whether the HTTP status was 2xx. You need to check both:
ts
const result = await fetch('https://api.example.com/data')
if (!result.ok) {
// Network error (no connection, DNS failure, etc.)
return
}
if (!result.value.ok) {
// HTTP error (404, 500, etc.)
console.error('HTTP', result.value.status)
return
}
const data = await result.value.json()POST request
ts
const result = await fetch('https://api.example.com/data', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({temperature: 23.5}),
})Request with timeout
ts
const result = await fetch('https://api.example.com/data', {
signal: AbortSignal.timeout(5000),
})
if (!result.ok && result.error.name === 'Aborted') {
console.error('Request timed out')
}On ESP32, aborting a request cancels the underlying HTTP task between read chunks and frees TLS buffers immediately.
Types
RequestInit
ts
interface RequestInit {
body?: string | null
headers?: HeadersInit
method?: string
signal?: AbortSignal | null
}Response
ts
interface Response {
readonly headers: Headers
readonly ok: boolean // true if status is 200-299
readonly redirected: boolean
readonly status: number
readonly statusText: string
readonly url: string
arrayBuffer(): Promise<ArrayBufferLike>
json(): Promise<any>
text(): Promise<string>
}Headers
Standard Headers interface with get, set, has, append, delete, forEach, and getSetCookie.
HeadersInit
ts
type HeadersInit = [string, string][] | Record<string, string> | HeadersErrors
FetchError
| Variant | Fields | Description |
|---|---|---|
TooManyPending | — | Too many concurrent requests |
TaskFailed | — | Internal task failure |
RequestFailed | message: string | Request failed (DNS, TLS, connection, timeout, etc.) |
Aborted | message: string | Request was cancelled via AbortSignal |