What does the .then() function mean in JavaScript?
I’ve come across code that looks like this:
myObj.doSome("task").then(function(env) {
// logic
});
Where does .then() come from, and how is it used in this context?
What does the .then() function mean in JavaScript?
I’ve come across code that looks like this:
myObj.doSome("task").then(function(env) {
// logic
});
Where does .then() come from, and how is it used in this context?
The .then() method is called on a Promise object. When you invoke a function that returns a Promise (like myObj.doSome(“task”)), you can use .then() to specify what should happen when the Promise resolves (i.e., completes successfully). The argument to .then() is a callback function that receives the resolved value of the Promise as its parameter.
myObj.doSome("task").then(function(env) {
console.log("Task completed with result:", env);
});
In this example, when the task is done, the value returned from the doSome method will be passed to the env parameter.
The .then() method can also return another Promise, allowing for chaining. This means you can perform multiple asynchronous operations in sequence. Each .then() can have its own callback function, and the next one will wait for the previous one to resolve.
myObj.doSome("task")
.then(function(env) {
console.log("First step completed:", env);
return anotherAsyncFunction(env); // returns a new Promise
})
.then(function(result) {
console.log("Second step completed with result:", result);
});
Here, the second .then() waits for the Promise returned by anotherAsyncFunction to resolve before executing its callback.
You can also handle errors in a Promise chain using .catch(). If any of the Promises in the chain reject, the control will move to the nearest .catch().
myObj.doSome("task")
.then(function(env) {
// some logic
})
.catch(function(error) {
console.error("An error occurred:", error);
});
In this example, if an error occurs at any point in the Promise chain, it will be caught by the .catch() method, allowing for centralized error handling.