Promise 是 JavaScript 中的一项强大功能,可以简化异步操作的处理。它们提供了一种更清晰、更直观的方式来处理异步代码,避免了“回调地狱”等问题。
A Promise 是一个对象,表示异步操作的最终完成(或失败)及其结果值。它允许您通过链接操作和有效处理错误来编写更易于管理的异步代码。
Promise 具有三种状态:
const promise = new Promise((resolve, reject) => { let success = true; // Change to false to simulate rejection if (success) { resolve("Operation was successful!"); } else { reject("Operation failed."); } }); promise .then((result) => console.log(result)) .catch((error) => console.error(error));
promise .then((result) => { console.log(result); return "Next Step"; }) .then((nextResult) => console.log(nextResult));
promise.catch((error) => console.error(error));
promise.finally(() => console.log("Cleanup actions."));
const promise1 = Promise.resolve(10); const promise2 = Promise.resolve(20); Promise.all([promise1, promise2]).then((results) => console.log(results));
const promise1 = Promise.resolve("Success"); const promise2 = Promise.reject("Error"); Promise.allSettled([promise1, promise2]).then((results) => console.log(results));
const promise1 = new Promise((resolve) => setTimeout(resolve, 500, "One")); const promise2 = new Promise((resolve) => setTimeout(resolve, 100, "Two")); Promise.race([promise1, promise2]).then((result) => console.log(result));
const promise1 = Promise.reject("Error 1"); const promise2 = Promise.resolve("Success"); const promise3 = Promise.reject("Error 2"); Promise.any([promise1, promise2, promise3]).then((result) => console.log(result));
链接可以按顺序处理多个异步操作。
fetch("https://api.example.com/data") .then((response) => response.json()) .then((data) => { console.log(data); return fetch("https://api.example.com/other-data"); }) .then((otherResponse) => otherResponse.json()) .then((otherData) => console.log(otherData)) .catch((error) => console.error("Error:", error));
错误通过 Promise 链传播,直到被 catch() 块捕获。
fetch("https://api.example.com/data") .then((response) => { if (!response.ok) throw new Error("Network response was not ok"); return response.json(); }) .then((data) => console.log(data)) .catch((error) => console.error("Error:", error));
您可以在这里探索 Promise 的详细现实用例:
JavaScript Promises 提供了一种稳健的方法来清晰、高效地处理异步操作。通过掌握 Promise,您可以编写更干净、更易于维护的代码,并避免像回调地狱这样的陷阱。开始练习上面的方法和示例,您将顺利掌握异步 JavaScript!
以上是JavaScript 中的 Pumble的详细内容。更多信息请关注PHP中文网其他相关文章!