Asynchronous code: callbacks and promises
Until now each line waited for the previous one to finish. But some tasks take time: requesting data from a server, reading a file, waiting for a timer. If the program stopped to wait, the page would freeze. JavaScript solves this with asynchrony: it starts the task, keeps running the rest of the code and, when the task finishes, runs the pending part. Understanding this model is what separates a beginner from someone who can already build real applications.
Callbacks and setTimeout
The oldest way is the callback: you pass a function that will run when the task ends. setTimeout(fn, ms) runs fn after ms milliseconds. Notice the output order in the example: even if the timer is zero milliseconds, its callback runs after all the synchronous code, because it enters a queue and waits until the call stack is empty. Nesting callbacks inside callbacks produces the so-called callback hell, pyramid-shaped code that is hard to read and to handle errors in.
console.log('1 - start');
setTimeout(() => {
console.log('3 - inside the timer');
}, 0);
console.log('2 - end of the synchronous code');
// Output order: 1, 2, 3Promises
A promise (Promise) is an object that represents a result that will arrive in the future. It has three states: pending, fulfilled (with a value) or rejected (with an error). It is created with new Promise and a function that receives resolve and reject. To consume it you use .then for success, .catch for the error and .finally, which always runs. The .then calls can be chained, and what one returns reaches the next; if an error happens at any link, it jumps to the nearest .catch.
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function divide(a, b) {
return new Promise((resolve, reject) => {
if (b === 0) reject(new Error('Cannot divide by zero'));
else resolve(a / b);
});
}
divide(10, 2)
.then((result) => {
console.log('Result:', result); // Result: 5
return result * 10;
})
.then((value) => console.log('Chained:', value)) // Chained: 50
.catch((error) => console.log('Error:', error.message))
.finally(() => console.log('Done'));
divide(1, 0)
.then((r) => console.log(r))
.catch((error) => console.log('Error:', error.message)); // Cannot divide by zero
wait(100).then(() => console.log('100 ms later'));Combining several promises
When several tasks are independent, it makes no sense to wait for them one after another. Promise.all receives an array of promises and returns another one that is fulfilled when all are fulfilled, with an array of results in the same order; if one fails, everything fails. Promise.allSettled waits for all of them and tells you which one was fulfilled and which was not, without failing. Promise.race returns the first one to finish, and it is useful to put a time limit on an operation. Tasks run at the same time, so the total time is that of the slowest one.
const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
Promise.all([delay(300, 'A'), delay(100, 'B'), delay(200, 'C')])
.then((results) => console.log(results)); // [ 'A', 'B', 'C' ] after ~300 ms
Promise.race([delay(300, 'slow'), delay(100, 'fast')])
.then((winner) => console.log(winner)); // fast
Promise.allSettled([delay(50, 'ok'), Promise.reject(new Error('boom'))])
.then((list) => console.log(list.map((r) => r.status))); // [ 'fulfilled', 'rejected' ]Typical mistakes with promises
The most frequent failure is forgetting return inside a .then: the chain continues, but the next link receives undefined. Another is mixing styles, nesting .then inside another .then instead of chaining them, which recreates callback hell. It is also common to create a promise with new Promise around something that already returns a promise; it is not needed, simply return it. Finally, remember that a promise starts running as soon as it is created, not when you add .then: creating the promise and waiting later does not delay the work.
✎ 我的笔记
仅保存在此浏览器中。登录后可保存到账号。0/5000 字符