Home >Web Front-end >JS Tutorial >How to use the then method of Promise object
The then method of Promise is used to handle asynchronous operations of Promise objects. In JS, Promise is a commonly used way to handle asynchronous operations. It provides a more convenient and clear syntax to handle asynchronous operations.
The basic usage of the then method is as follows:
promise.then(onFulfilled, onRejected);
Among them, onFulfilled is the callback function when the Promise is successful, and is called when the status of the Promise object changes to Fulfilled (completed); onRejected is The callback function when a Promise fails, called when the status of the Promise object changes to Rejected.
Specifically, when the state of the Promise object is Fulfilled, the onFulfilled function is called and the value inside the Promise is passed to it as a parameter. When the state of the Promise object is Rejected, the onRejected function will be called and the error information inside the Promise will be passed to it as a parameter.
The following is a simple sample code showing the use of Promise's then method:
function fetchData() { return new Promise((resolve, reject) => { // 模拟异步请求 setTimeout(() => { const data = 'Hello World!'; resolve(data); // 成功时调用resolve,传递数据 // reject('Error occurred'); // 失败时调用reject,传递错误信息 }, 1000); }); } fetchData() .then((data) => { console.log('成功:', data); }) .catch((error) => { console.error('失败:', error); });
In the above example, we define a fetchData function, which returns a Promise object. In the Promise constructor, we simulate an asynchronous request and return data or error after 1 second. Change the state of a Promise by calling resolve or reject.
In the main program, we call the fetchData function, and register the callback function for success through the then method and the callback function for failure through the catch method. When the asynchronous operation in the fetchData function is completed, the corresponding callback function will be called based on the returned result.
It should be noted that the then method returns a new Promise object. By calling the then method in a chain, multiple asynchronous operations can be processed sequentially.
In short, the then method of Promise is a callback function used to handle the success and failure status of the Promise object. It provides a convenient way to handle asynchronous operations and makes the code more readable.
The above is the detailed content of How to use the then method of Promise object. For more information, please follow other related articles on the PHP Chinese website!