乐闻世界logo
搜索文章和话题

How Does Promise Implement Chained Calls?

浏览0
2024年6月24日 16:43

Promise implements chained calls primarily by returning a new Promise object.

In JavaScript, a Promise is an object for handling asynchronous operations, enabling synchronous handling of asynchronous results at the original call site.

Below is the basic implementation of Promise chained calls:

  1. The Promise constructor accepts an executor function, which takes two parameters: resolve and reject, used for successful and failed asynchronous operations respectively.
  2. Calling the .then() method on a Promise object enables chained calls. The .then() method takes two optional parameters: onFulfilled and onRejected, which are invoked when the Promise resolves or rejects respectively. The .then() method also returns a Promise object to facilitate chained calls.
  3. If onFulfilled or onRejected returns a value x, the Promise Resolution Procedure is executed: [Promise Resolution Procedure].
  4. If onFulfilled or onRejected throws an exception e, the Promise returned by Promise.then() is rejected.
  5. If onFulfilled is not a function and the previous promise resolves successfully, the next promise successfully processes the final state of the previous promise.
  6. If onRejected is not a function and the previous promise rejects, the next promise rejects with the reason from the previous promise.

The following is an example:

javascript
new Promise(function(resolve, reject) { setTimeout(() => resolve(1), 1000); // Step 1: Create a Promise and execute an asynchronous operation }).then(function(result) { // Step 2: Register an onFulfilled callback console.log(result); // Output: 1 return result + 2; }).then(function(result) { // Step 3: Chained call console.log(result); // Output: 3 return result + 2; }).then(function(result) { console.log(result); // Output: 5 return result + 2; });

In this example, each .then() call returns a new Promise object, which is immediately executed and invokes the next .then() registered callback upon completion. This allows synchronous handling of asynchronous results, which is the essence of Promise chained calls.

标签:前端ES6Promise