Skip to content

Synchronous vs Asynchronous

Synchronous code runs one statement at a time, in order, and each statement finishes before the next one starts. Asynchronous code starts a task, such as a timer or a network request, and carries on at once; the result is handled later by a callback or a promise, after the current code has finished.

JavaScript runs your code on a single thread, so a slow synchronous task blocks everything else, including the page’s response to clicks. Anything that waits on the outside world is therefore asynchronous: timers, fetch(), file and database access, user events and geolocation.

Each call here returns its value before the next line runs, so the output follows the source:

const addVat = (net) => net * 1.2;
const format = (amount) => `£${amount.toFixed(2)}`;
console.log('start');
console.log(format(addVat(10)));
console.log('end');

This prints:

start
£12.00
end

setTimeout() hands its callback to the runtime and returns immediately. Even with a delay of 0, the callback runs only after the current code has finished, so the line after it sees the old value:

let stock = 5;
console.log('order placed');
setTimeout(() => {
stock--;
console.log(`stock updated: ${stock}`);
}, 0);
console.log(`stock now: ${stock}`);

This prints:

order placed
stock now: 5
stock updated: 4

A promise stands for a result that is not ready yet. It starts pending, and you attach a callback with then() to run once it is fulfilled:

const loadBasket = () =>
new Promise((resolve) => {
setTimeout(() => resolve(['tea', 'milk']), 50);
});
const pending = loadBasket();
console.log(pending);
pending.then((items) => {
console.log('loaded:', items);
console.log(pending);
});
console.log('waiting...');

This prints in Node.js, and a browser’s console shows the same states in a slightly different format:

Promise { <pending> }
waiting...
loaded: [ 'tea', 'milk' ]
Promise { [ 'tea', 'milk' ] }

Promise callbacks and timer callbacks wait in different queues. When the current code finishes, all waiting promise callbacks run before the next timer callback, so a promise that is already settled beats a zero-delay timer:

console.log('1 sync');
setTimeout(() => console.log('4 timer'), 0);
Promise.resolve().then(() => console.log('3 promise'));
console.log('2 sync');

This prints:

1 sync
2 sync
3 promise
4 timer

Event Loops explains the queues, and the JavaScript Promises series covers promises in more depth.

Steve Griffith covers this topic in his video Understanding Synchronous vs Asynchronous JavaScript.