Ts Promise
Promise is the foundation of JavaScript asynchronous programming, and TypeScript provides complete type support for Promise.\\n\\nThrough generic parameters, you can precisely specify the types of a Promise's resolved and rejected values.\\n\\n* * *\\n\\n* * *\\n\\n## Why We Need Promise\\n\\nIn JavaScript, many operations are asynchronous, such as network requests, file reading, timers, etc.\\n\\nPromise provides a unified asynchronous programming interface, making asynchronous code easier to write and manage.\\n\\nTypeScript ensures the type safety of Promises through generic support.\\n\\n> **Concept Explanation:** Promise is an object that represents the eventual result of an asynchronous operation. It has three states: pending, fulfilled, and rejected.\\n\\n* * *\\n\\n## Creating a Promise\\n\\nUse the Promise constructor to create a Promise, passing in an executor function.\\n\\n## Instance\\n\\n// Create a Promise, using generics to specify the type of the resolved value\\n\\n// Promise Returns a string on success\\n\\nvar promise =new Promise(function(resolve, reject){\\n\\nvar success =true;\\n\\nif(success){\\n\\n// Calling resolve indicates operation success, passing the result value\\n\\n resolve("Success!");\\n\\n}else{\\n\\n// Calling reject indicates operation failure, passing errors\\n\\n reject(new Error("Failure"));\\n\\n}\\n\\n});\\n\\n// Use then to handle success cases\\n\\n promise.then(function(value){\\n\\n console.log("Completed: "+ value);\\n\\n})(function(error){\\n\\n// Use catch to handle failure cases\\n\\n console.log("Errors: "+ error.message);\\n\\n});\\n\\n**Running Result:**\\n\\nCompleted: Success!\\n> **Generic Explanation:** The `T` in `Promise` is the type of the value when the Promise is successfully resolved. This allows TypeScript to infer the type of the return value.\\n\\n* * *\\n\\n## Promise Chaining\\n\\nThe then and catch methods return new Promises, allowing for chaining.\\n\\n## Instance\\n\\n// ChainingChained call: each then returns a new value, which is received by the next then\\n\\nvar promise = Promise.resolve(1)\\n\\n .then(function(n){\\n\\n// First then, n = 1\\n\\nreturn n *2;// Returns 2\\n\\n})\\n\\n .then(function(n){\\n\\n// Second then, n = 2\\n\\nreturn n +10;// Returns 12\\n\\n})\\n\\n .then(function(n){\\n\\n// Third then, n = 12\\n\\n console.log("Final Result: "+ n);\\n\\nreturn n;\\n\\n});\\n\\nconsole.log("Promise Chaining: "+ promise);\\n\\n**Running Result:**\\n\\nFinal Result: 12Promise Chaining: \\n> **Chaining:** Each then returns a new Promise, which allows us to execute multiple asynchronous operations in sequence.\\n\\n* * *\\n\\n## Promise.all\\n\\nPromise.all waits for all Promises to complete and returns an array containing all the results.\\n\\n## Instance\\n\\n// Create three Promises\\n\\nvar p1 = Promise.resolve(1);\\n\\nvar p2 = Promise.resolve(2);\\n\\nvar p3 = Promise.resolve(3);\\n\\n// Promise.all Wait for all Promises to complete\\n\\n// Returns an array containing the results of all Promises\\n\\n Promise.all([p1, p2, p3]).then(function(results){\\n\\n console.log("All completed: "+ results);\\n\\n// Calculate sum\\n\\n console.log("Sum: "+ results.reduce(function(a, b){return a + b;},0));\\n\\n});\\n\\n**Running Result:**\\n\\nAll completed: 1,2,3Sum: 6\\n> **Note:** If any Promise fails, Promise.all will immediately reject and will not wait for the other Promises to complete.\\n\\n* * *\\n\\n## Promise.race\\n\\nPromise.race returns the result of the Promise that completes first (whether resolved or rejected).\\n\\n## Instance\\n\\n// Create three Promises with different delays\\n\\nvar p1 =new Promise(function(resolve){\\n\\n setTimeout(function(){ resolve("p1");},100);\\n\\n});\\n\\nvar p2 =new Promise(function(resolve){\\n\\n setTimeout(function(){ resolve("p2");},50);\\n\\n});\\n\\nvar p3 =new Promise(function(resolve){\\n\\n setTimeout(function(){ resolve("p3");},30);\\n\\n});\\n\\n// Promise.race Return the result of the first completed Promise\\n\\n Promise.race([p1, p2, p3]).then(function(value){\\n\\n console.log("First completed: "+ value);\\n\\n});\\n\\n**Running Result:**\\n\\nFirst completed: p3\\n> **Use Case:** Promise.race is often used to implement timeout functionality: racing a long-running operation Promise against a timeout Promise.\\n\\n* * *\\n\\n## Promise.allSettled\\n\\nPromise.allSettled waits for all Promises to finish (whether resolved or rejected) and returns the status and result of each Promise.\\n\\n## Instance\\n\\n// Create three PromisesοΌOne of them will fail\\n\\nvar p1 = Promise.resolve("Success");\\n\\nvar p2 = Promise.reject(new Error("Failure"));\\n\\nvar p3 = Promise.resolve("Completed");\\n\\n// Promise.allSettled Wait for all Promises to finish\\n\\n// Returns the state and value/reason of each Promise\\n\\n Promise.allSettled([p1, p2, p3]).then(function(results){\\n\\n results.forEach(function(result, index){\\n\\nif(result.status==="fulfilled"){\\n\\n console.log("Promise "+ index +": "+ result.value);\\n\\n}else{\\n\\n console.log("Promise "+ index +": "+ result.reason.message);\\n\\n}\\n\\n});\\n\\n});\\n\\n**Running Result:**\\n\\nPromise 0: SuccessPromise 1: Failed Promise 2: Completed\\n> **Difference:** Promise.all stops immediately upon the first failure; Promise.allSettled waits for all Promises to finish.\\n\\n* * *\\n\\n## Promise Type Annotations\\n\\nTypeScript's generic support makes Promise type declarations precise.\\n\\n## Instance\\n\\n// Define a function that returns a Promise\\n\\n// Promise<{ name: string; age: number }> Specifies the type of the returned User object\\n\\nfunction getUser(): Promise<{ name: string; age: number }>{\\n\\nreturn Promise.resolve({ name:"Alice", age:25});\\n\\n}\\n\\n// async Function: implicitly returns a Promise\\n\\n async function main(){\\n\\n// await Automatically infers the type of user\\n\\nvar user = await getUser();\\n\\n console.log("User: "+ JSON.stringify(user));\\n\\n}\\n\\nmain();\\n\\n> **Type Inference:** TypeScript automatically infers the return type of a Promise based on the generic parameter, which allows us to get complete type hints in async/await as well.\\n\\n* * *\\n\\n## Precautions\\n\\n* **Generic Parameters:** Always specify generic parameters for Promises to clarify the return type\\n* **Error Handling:** Remember to use catch to handle Promise rejection cases\\n* **all vs allSettled:** Use allSettled when you need all results, and all when you need fast failure\\n* **async/await:** Modern code recommends using async/await for more concise syntax\\n\\n> **Best Practice:** Prefer the async/await syntax; it is still fundamentally based on Promises, but reads like synchronous code.\\n\\n* * *\\n\\n## Summary\\n\\nPromise is the core of TypeScript asynchronous programming.\\n\\n* **Promise:** Asynchronous operation container, with three states: pending/fulfilled/rejected\\n* **then/catch:** Chain handling of asynchronous results\\n* **Promise.all:** Waits for all to complete; fails entirely if any one fails\\n* **Promise.race:** Returns the result of the first one to complete\\n* **Promise.allSettled:** Waits for all to finish and returns the status of each\\n\\n> **Suggestion:** Use the async/await syntax with Promises to make asynchronous code both type-safe and easy to read.\\n\\nx
YouTip