JavaScript Callbacks and Promises
JavaScript runs one line at a time, but some tasks take time, like a timer or a request to a server. Asynchronous code lets the program continue while it waits.
setTimeout and callbacks
console.log("1. Start");
setTimeout(() => {
console.log("3. After 1 second");
}, 1000);
console.log("2. End of the code");
1. Start
2. End of the code
3. After 1 second
The function inside setTimeout is a callback. JavaScript does not wait; it goes on and calls it later.
When one task depends on the previous one, callbacks get nested deeper and deeper, which is called callback hell and is hard to read. Promises solve this.
Promises
A Promise is an object for a value that will come in the future. It is in one of three states: pending, fulfilled (success) or rejected (error).
function wait(ms) {
return new Promise((resolve, reject) => {
if (ms < 0) {
reject(new Error("Time cannot be negative"));
} else {
setTimeout(() => resolve("Waited " + ms + " ms"), ms);
}
});
}
wait(500)
.then(message => console.log(message))
.catch(error => console.log("Error: " + error.message))
.finally(() => console.log("Done"));
Waited 500 ms
Done
.then()runs when the promise is fulfilled..catch()runs when it is rejected (or something throws)..finally()runs in both cases.
Chain promises
wait(100)
.then(m => {
console.log(m);
return wait(200);
})
.then(m => console.log(m));
Waited 100 ms
Waited 200 ms
Promise.all
Runs many promises at the same time and waits for all of them.
Promise.all([wait(100), wait(300)]).then(results => {
console.log(results);
});
[ "Waited 100 ms", "Waited 300 ms" ]
Summary
- Asynchronous code lets the program continue while it waits.
- A promise is pending, fulfilled or rejected, and you use
then,catchandfinally. Promise.allwaits for many promises.- Next: Async/Await and Fetch.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |