2024年6月24日 16:43

How to Use the resolve Function in Promise?

In JavaScript, the Promise object is a solution for asynchronous programming. A Promise starts in the pending (waiting) state upon creation and can transition to the fulfilled (successful) state via its resolve function or to the rejected (failed) state via its reject function.

To utilize the resolve function of Promise, it is typically called when an asynchronous operation completes successfully. Below is a simple example demonstrating how to use the resolve function of Promise:

javascript
function asyncOperation() { // Create a new Promise object return new Promise((resolve, reject) => { // Execute the asynchronous operation setTimeout(() => { const operationWasSuccessful = true; // Assume this is based on the result of the asynchronous operation if (operationWasSuccessful) { resolve('Operation successful'); // If the operation succeeds, call resolve and pass the result } else { reject('Operation failed'); // If the operation fails, call reject and pass the error message } }, 1000); // Assume this asynchronous operation takes 1 second }); } asyncOperation() .then(result => { console.log(result); // Log the successful result }) .catch(error => { console.error(error); // Log the error message });

In the above code, the asyncOperation function returns a new Promise object. Within the Promise constructor, there are two parameters: resolve and reject. These parameters are also functions used to handle the success and failure cases of the asynchronous operation respectively.

If the asynchronous operation succeeds (in this example, we assume operationWasSuccessful is true), then the resolve function is called and the result message 'Operation successful' is passed. This causes the Promise object to transition to the fulfilled state and pass the result to the callback function of the subsequent .then method.

If the asynchronous operation fails, the reject function is called and the error message 'Operation failed' is passed. This causes the Promise object to transition to the rejected state and pass the error message to the callback function of the subsequent .catch method.

标签:JavaScript前端Promise