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:
- The Promise constructor accepts an executor function, which takes two parameters:
resolveandreject, used for successful and failed asynchronous operations respectively. - Calling the
.then()method on a Promise object enables chained calls. The.then()method takes two optional parameters:onFulfilledandonRejected, which are invoked when the Promise resolves or rejects respectively. The.then()method also returns a Promise object to facilitate chained calls. - If
onFulfilledoronRejectedreturns a valuex, the Promise Resolution Procedure is executed: [Promise Resolution Procedure]. - If
onFulfilledoronRejectedthrows an exceptione, the Promise returned byPromise.then()is rejected. - If
onFulfilledis not a function and the previous promise resolves successfully, the next promise successfully processes the final state of the previous promise. - If
onRejectedis not a function and the previous promise rejects, the next promise rejects with the reason from the previous promise.
The following is an example:
javascriptnew 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.