ホームページ >ウェブフロントエンド >jsチュートリアル >JavaScript: Promise 完全ガイド
Promise は、非同期プログラミングの新しいソリューションです。 ES6 はこれを言語標準に組み込み、その使用法を統一し、Promise オブジェクトをネイティブに提供します。
その導入により、非同期プログラミングの苦境が大幅に改善され、コールバック地獄が回避されました。これは、コールバック関数やイベントなどの従来のソリューションよりも合理的かつ強力です。
Promise は、簡単に言えば、将来完了するイベント (通常は非同期操作) の結果を保持するコンストラクターです。構文的には、Promise は非同期操作メッセージを取得できるオブジェクトです。 Promise は統合された API を提供し、さまざまな非同期操作を同じ方法で処理できるようにします。
ES5 のコールバック地獄の問題を効果的に解決できます (深くネストされたコールバック関数を回避します)。
統一標準に従っており、簡潔な構文、優れた可読性、保守性を備えています。
Promise オブジェクトはシンプルな API を提供し、非同期タスクの管理をより便利かつ柔軟にします。
Promise を使用する場合、次の 3 つの状態に分類できます。
保留中: 保留中。これは初期状態であり、Promise は履行も拒否もされていません。
満たされました: 満たされました/解決されました/成功。 solve() が実行されると、Promise はすぐにこの状態になり、解決されてタスクが正常に完了したことを示します。
rejected: 拒否/失敗。 request() が実行されると、Promise はすぐにこの状態になり、拒否されてタスクが失敗したことを示します。
new Promise() が実行されると、Promise オブジェクトの状態は初期状態である pending に初期化されます。新しい Promise() 行のかっこ内の内容は同期的に実行されます。括弧内では、resolve と request の 2 つのパラメーターを持つ非同期タスクの関数を定義できます。例:
// Create a new promise const promise = new Promise((resolve, reject) => { //promise's state is pending as soon as entering the function console.log('Synchronous Operations'); //Begin to execute asynchronous operations if (Success) { console.log('success'); // If successful, execute resolve() to switch the promise's state to Fulfilled resolve(Success); } else { // If failed, excecute reject() to pass the error and switch the state to Rejected reject(Failure); } }); console.log('LukeW'); //Execute promise's then():to manage success and failure situations promise.then( successValue => { // Process promise's fulfilled state console.log(successValue, 'successfully callback'); // The successMsg here is the Success in resolve(Success) }, errorMsg => { //Process promise's rejected state console.log(errorMsg, 'rejected'); // The errorMsg here is the Failure in reject(Failure) } );
Promise コンストラクターは、関数をパラメーターとして受け取ります。この関数には、resolve と拒否の 2 つの引数があります。
const promise = new Promise((resolve, reject) => { // ... some code if (/* Success */){ resolve(value); } else { reject(error); } });
Promise.resolve(value) の戻り値も Promise オブジェクトであり、.then 呼び出しでチェーンできます。コードは次のとおりです:
Promise.resolve(11).then(function(value){ console.log(value); // print 11 });
resolve(11) コードでは、promise オブジェクトが解決された状態に遷移し、引数 11 を後続の .then で指定された onFulfilled 関数に渡します。 Promise オブジェクトは、新しい Promise 構文を使用するか、Promise.resolve(value).
を使用して作成できます。function testPromise(ready) { return new Promise(function(resolve,reject){ if(ready) { resolve("hello world"); }else { reject("No thanks"); } }); }; testPromise(true).then(function(msg){ console.log(msg); },function(error){ console.log(error); });
上記のコードの意味は、promise オブジェクトを返す testPromise メソッドに引数を渡すことです。引数が true の場合、Promise オブジェクトのsolve() メソッドが呼び出され、それに渡されたパラメータが後続の .then の最初の関数に渡され、出力「hello world」が生成されます。引数が false の場合、promise オブジェクトの拒否() メソッドが呼び出され、.then の 2 番目の関数がトリガーされ、「No thanks.」という出力が生成されます。
then メソッドは 2 つのコールバック関数をパラメータとして受け入れることができます。最初のコールバック関数は、Promise オブジェクトの状態が解決済みに変化したときに呼び出され、2 番目のコールバック関数は、Promise オブジェクトの状態が拒否に変化したときに呼び出されます。 2 番目のパラメータはオプションであり、省略できます。
then メソッドは、(元の Promise インスタンスではなく) 新しい Promise インスタンスを返します。したがって、最初のメソッドの後に別の then メソッドが呼び出される、連鎖構文を使用できます。
非同期イベントを順番に記述する必要があり、それらを逐次的に実行する必要がある場合は、次のように記述できます。
let promise = new Promise((resolve,reject)=>{ ajax('first').success(function(res){ resolve(res); }) }) promise.then(res=>{ return new Promise((resovle,reject)=>{ ajax('second').success(function(res){ resolve(res) }) }) }).then(res=>{ return new Promise((resovle,reject)=>{ ajax('second').success(function(res){ resolve(res) }) }) }).then(res=>{ })
Then メソッドに加えて、Promise オブジェクトには catch メソッドもあります。このメソッドは then メソッドの 2 番目のパラメータに相当し、reject のコールバック関数を指します。ただし、catch メソッドには追加機能があります。resolve コールバック関数の実行中にエラーが発生したり、例外がスローされた場合でも、実行は停止されません。代わりに、catch メソッドに入ります。
p.then((data) => { console.log('resolved',data); },(err) => { console.log('rejected',err); } ); p.then((data) => { console.log('resolved',data); }).catch((err) => { console.log('rejected',err); });
The all method can be used to complete parallel tasks. It takes an array as an argument, where each item in the array is a Promise object. When all the Promises in the array have reached the resolved state, the state of the all method will also become resolved. However, if even one of the Promises changes to rejected, the state of the all method will become rejected.
let promise1 = new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(1); },2000) }); let promise2 = new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(2); },1000) }); let promise3 = new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(3); },3000) }); Promise.all([promise1,promise2,promise3]).then(res=>{ console.log(res); //result:[1,2,3] })
When the all method is called and successfully resolves, the result passed to the callback function is also an array. This array stores the values from each Promise object when their respective resolve functions were executed, in the order they were passed to the all method.
The race method, like all, accepts an array where each item is a Promise. However, unlike all, when the first Promise in the array completes, race immediately returns the value of that Promise. If the first Promise's state becomes resolved, the race method's state will also become resolved; conversely, if the first Promise becomes rejected, the race method's state will become rejected.
let promise1 = new Promise((resolve,reject)=>{ setTimeout(()=>{ reject(1); },2000) }); let promise2 = new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(2); },1000) }); let promise3 = new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(3); },3000) }); Promise.race([promise1,promise2,promise3]).then(res=>{ console.log(res); //result:2 },rej=>{ console.log(rej)}; )
So, what is the practical use of the race method? When you want to do something, but if it takes too long, you want to stop it; this method can be used to solve that problem:
Promise.race([promise1,timeOutPromise(5000)]).then(res=>{})
The finally method is used to specify an operation that will be executed regardless of the final state of the Promise object. This method was introduced in the ES2018 standard.
promise .then(result => {···}) .catch(error => {···}) .finally(() => {···});
In the code above, regardless of the final state of the promise, after the then or catch callbacks have been executed, the callback function specified by the finally method will be executed.
In work, you often encounter a requirement like this: for example, after sending an A request using AJAX, you need to pass the obtained data to a B request if the first request is successful; you would need to write the code as follows:
let fs = require('fs') fs.readFile('./a.txt','utf8',function(err,data){ fs.readFile(data,'utf8',function(err,data){ fs.readFile(data,'utf8',function(err,data){ console.log(data) }) }) })
The above code has the following drawbacks:
The latter request depends on the success of the previous request, where the data needs to be passed down, leading to multiple nested AJAX requests, making the code less intuitive.
Even if the two requests don't need to pass parameters between them, the latter request still needs to wait for the success of the former before executing the next step. In this case, you also need to write the code as shown above, which makes the code less intuitive.
After the introduction of Promises, the code becomes like this:
let fs = require('fs') function read(url){ return new Promise((resolve,reject)=>{ fs.readFile(url,'utf8',function(error,data){ error && reject(error) resolve(data) }) }) } read('./a.txt').then(data=>{ return read(data) }).then(data=>{ return read(data) }).then(data=>{ console.log(data) })
This way, the code becomes much more concise, solving the problem of callback hell.
以上がJavaScript: Promise 完全ガイドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。