Today, I was following a WordPress tutorial, and the instructor was demonstrating how to search the site using jQuery and JavaScript, specifically using the .then() and .when() methods. As I followed along, I realized that I wasn’t as familiar with these methods as I thought.
So, I did a bit of research, took some notes, and added them to my Obsidian notebook. To be honest, the notes are kind of rough—they look like something a fifth grader with the attention span of a squirrel might put together (which, let's face it, sometimes feels like me!).
But I figured, why not share them? If they help even one person, it’s worth posting.
You're at school, and you and your friends make promises to each other. These promises are like saying, “I’ll finish my homework, and then we can play games.”
But here's the thing: sometimes it takes a little while to finish the homework. You might finish it fast, or maybe your dog eats it, and you never finish (oops!). JavaScript promises work the same way. It waits for something to happen, and then it says, “Okay, what next?”
The .then() method is like what you’ll do after the promise is done. Imagine you say to your friend:
But what if you don’t finish? Uh-oh, you can add a backup plan:
Here’s how you would say this in JavaScript:
promiseToFinishHomework .then(() => { console.log("Yay! We can play games!"); // If you finished }) .catch(() => { console.log("Oh no! No games today!"); // If you didn’t finish });
This is like when you’re waiting for a bunch of your friends to finish their homework so you can all play together. You’re like:
In real life, that’s called working together. In JavaScript, you use something called Promise.all() (which is just like saying "Let's wait for everyone to be ready!"):
Promise.all([friend1, friend2]).then(() => { console.log("We’re all done! Time to play!"); });
So, JavaScript is just making sure it knows what happens next when promises are kept—or broken! ?
The promise doesn’t check the homework by itself. You tell it! When you create a promise, you decide if it’s resolved or rejected based on whether the task (like finishing homework) is done or not. The .then() runs when the promise is resolved, and .catch() runs when it’s rejected.
Here’s a full example to see it in action:
let promiseToFinishHomework = new Promise((resolve, reject) => { let finishedHomework = true; // Change this to false to see the rejection if (finishedHomework) { resolve(); // Homework is done! } else { reject(); // Homework is not done! } }); promiseToFinishHomework .then(() => { console.log("Yay! We can play games!"); // If the promise resolves (homework done) }) .catch(() => { console.log("Oh no! No games today!"); // If the promise rejects (homework not done) });
The above is the detailed content of JavaScript the .then / .when method.. For more information, please follow other related articles on the PHP Chinese website!