Promise は、非同期操作の処理を簡素化する JavaScript の強力な機能です。これらは、非同期コードを操作するためのよりクリーンで直感的な方法を提供し、「コールバック地獄」のような問題を回避します。
Promise は、非同期操作の最終的な完了 (または失敗) とその結果の値を表すオブジェクトです。操作を連鎖させ、エラーを効果的に処理することで、より管理しやすい非同期コードを作成できます。
Promise には 3 つの状態があります:
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));
エラーは、catch() ブロックによって捕捉されるまで、Promise チェーンを通じて伝播します。
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 Promise は、非同期操作を明確かつ効率的に処理するための堅牢な方法を提供します。 Promise をマスターすることで、よりクリーンで保守しやすいコードを記述し、コールバック地獄のような落とし穴を避けることができます。上記の方法と例を使って練習を始めれば、非同期 JavaScript の習得に向けて順調に進むでしょう!
以上がJavaScript でのパンブルの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。