You open a ride-hailing app, and the list of drivers near you appears one second later. During that second the app does not freeze: you can still move the map and tap buttons. The app asked a server (another computer that stores the data) for it. While it waited for the reply, the app continued with other work.
Asking a server for data over the internet takes time, and JavaScript does not stop and wait. It continues to the next line, and handles the result only when the server's reply arrives. fetch() is the modern way to send a request for data (an HTTP request) from the browser to a server.
Ask for data with fetch
The code below asks a server for one student's data, then prints the student's name:
fetch('https://api.example.com/students/1')
.then((res) => {
if (!res.ok) throw new Error('HTTP ' + res.status)
return res.json()
})
.then((data) => {
console.log('Name:', data.name)
})
.catch((err) => {
console.log('Failed:', err.message)
})
console.log('Waiting for a reply...')
Guess first: does console.log('Waiting for a reply...') on the last line print first or last?
What prints, in order:
Waiting for a reply...
Name: Budi
The last line prints first. fetch sends the request and does not wait for the reply, so JavaScript continues directly to that line. Only when the server's reply arrives do the functions inside .then run.
fetch(url)asks for the data at the addressurland returns a Promise right away: a container for a result that does not exist yet. A Promise works like a queue number. You hold the number now, and you receive the result later, when that number is called..then((res) => ...)runs when the reply arrives, andresholds that reply.res.okistruewhen the server replied with success, andres.statusholds the reply's code.res.json()reads the reply's content as JSON. The result ofres.json()is a Promise too, so the code returns it and the next.thenreceives it..then((data) => ...)receives the data, already turned into the object{ name: 'Budi', age: 17 }..catch((err) => ...)runs if anything fails infetchor in a.thenabove it.
fetch fails by itself only when the reply never reaches your code. For example, when you are offline, when the server name in the address is mistyped, or when the browser blocks the reply because of CORS rules (the server's permission for pages from other sites). err.message rarely names the cause, but the browser writes it in the Console. A 404 reply (data not found) still counts as a success, so it still goes into .then. That is why the code above checks res.ok, then throws its own error with throw.
Sending data with POST. With no extra settings, fetch only asks for data (a GET request). To send data, such as a new student, add an object of settings as the second argument:
fetch('https://api.example.com/students', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Sari', age: 16 })
})
.then((res) => {
if (!res.ok) throw new Error('HTTP ' + res.status)
return res.json()
})
.then((data) => console.log('Saved, id:', data.id))
.catch((err) => console.log('Failed:', err.message))
method: 'POST'changes the type of request to POST: sending new data.headerstells the server that the data being sent is JSON.bodyis the data.JSON.stringifyturns the object into JSON text, becausefetchsends text.
Make your own Promise
The function checkStock below returns a Promise of its own. That Promise succeeds when there is stock, and fails when there is none:
function checkStock(amount) {
return new Promise((resolve, reject) => {
if (amount > 0) {
resolve('In stock')
} else {
reject('Out of stock')
}
})
}
checkStock(3).then((result) => console.log(result)) // In stock
checkStock(0).catch((reason) => console.log(reason)) // Out of stock
new Promise(...)takes one function. JavaScript gives that function two other functions:resolveandreject.resolve(value)marks the Promise as successful. The value reaches.then.reject(reason)marks the Promise as failed. The reason reaches.catch.- Call one of the two. A plain
returninside that function does not finish the Promise. - In real code, write
reject(new Error('Out of stock')). Thenerr.messagein.catch((err) => ...)holdsOut of stock. If you giverejectplain text,err.messageisundefined.
A Promise always has one of three states: pending (still waiting), fulfilled (succeeded, through resolve) or rejected (failed, through reject). Once a Promise has succeeded or failed, its state never changes again.
A Promise that finishes after a pause
If you call resolve inside the function that setTimeout(fn, ms) schedules, the Promise finishes only after a pause of ms milliseconds:
function waitThen(message) {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Message: ' + message)
}, 500)
})
}
waitThen('ready').then((result) => console.log(result))
console.log('Start')
It prints Start first. Half a second later it prints Message: ready. If you write resolve outside the setTimeout, the Promise finishes with no pause.
⚠️ A Promise mistaken for data, and failures nobody notices
- Expecting
fetchto give you the data directly.const data = fetch(url)puts a Promise indata, not the data itself. Take the data inside.then, or useawait, which the next lesson covers. - No
.catch. When a Promise fails, the console shows "Uncaught (in promise)", and the user gets no message at all. - Not checking
res.ok. Without that check, a404reply is processed as if the data were there. res.json()reading an HTML page. When the server exists but the rest of the address is wrong, many servers reply with an HTML page. HTML is not JSON, sores.json()fails withSyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON. Check the address, then look at the server's reply in the Network tab (press F12).
TL;DR: fetch(url) asks a server (another computer) for the data at url and returns a Promise right away: a container for a result that arrives later. The code after fetch runs first. The result is handled later in .then, and a failure in .catch. Check res.ok on the server's reply (res), because a 404 reply (data not found) does not count as a failure. Make your own Promise with new Promise((resolve, reject) => ...): call resolve(value) for success, or reject(reason) for failure. A Promise's state starts as pending (waiting), then becomes fulfilled (succeeded) or rejected (failed).
⚡ fetch doesn't wait
Write:
fetch('https://api.example.com/students/1')
.then((res) => res.json())
.then((data) => console.log('Name:', data.name))
.catch((err) => console.log('Failed:', err.message))
console.log('Waiting for a reply...')
Guess first: fetch asks a server (another computer) for data, and that takes time. Does the last line print first or last?
First. fetch does not wait for the server's reply, so JavaScript continues directly to the next line. Name: Budi prints only when the server's reply arrives.
Meaning: fetch returns a Promise right away: a container for a result that does not exist yet. The first .then runs when the server's reply arrives, with that reply in res. res.json() reads its content as JSON, then the second .then receives the data. .catch runs if anything fails in fetch or in a .then.
⚡ A 404 still counts as a success
Write:
if (!res.ok) throw new Error('HTTP ' + res.status)
Meaning: res.ok is true when the server replied with success, and res.status holds the reply's code. fetch fails by itself only when the reply never reaches your code, for example when you are offline, when the server name is mistyped, or when the browser blocks the reply because of CORS rules (the server's permission). The Console shows the cause. A 404 reply (data not found) still goes into .then. So in the first .then, check res.ok, then throw your own error with throw, so that .catch handles it.
⚡ Make your own Promise
Write:
function checkStock(amount) {
return new Promise((resolve, reject) => {
if (amount > 0) {
resolve('In stock')
} else {
reject('Out of stock')
}
})
}
Meaning: new Promise(...) makes a Promise of your own. resolve(value) marks the Promise as successful, and the value reaches .then. reject(reason) marks the Promise as failed, and the reason reaches .catch. The Promise's state is pending (waiting) first, then fulfilled (succeeded) or rejected (failed).