Promise 是非同步程式設計的一種新解決方案。 ES6已將其納入語言標準,統一其用法並原生提供Promise物件。
它的引入極大地改善了非同步程式設計的困境,避免了回調地獄。它比回調函數和事件等傳統解決方案更合理、更強大。
Promise,簡單地說,是一個建構函數,它保存將來將完成的事件(通常是非同步操作)的結果。從語法上來說,Promise 是一個可以從中檢索非同步操作訊息的物件。 Promise 提供了統一的 API,允許以相同的方式處理各種非同步操作。
可以有效解決ES5中的回調地獄問題(避免回呼函數深度巢狀)。
遵循統一標準,語法簡潔,可讀性強,可維護性強。
Promise 物件提供了簡單的 API,讓管理非同步任務更方便、更靈活。
使用 Promise 時,我們可以將其分為三種狀態:
待處理:待處理。這是初始狀態,Promise 既沒有被履行,也沒有被拒絕。
已完成:已完成/已解決/成功。當執行resolve()時,Promise立即進入該狀態,表示已解決,任務已成功完成。
拒絕:拒絕/失敗。當執行reject()時,Promise立即進入該狀態,表示已被拒絕,任務失敗。
當執行new Promise()時,promise物件的狀態被初始化為pending,這是它的初始狀態。 new Promise()行括號內的內容是同步執行的。在括號內,您可以為非同步任務定義一個函數,該函數有兩個參數:resolve 和reject。例如:
// 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 和reject。
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物件轉換到resolved狀態,將參數11傳遞給後續.then中指定的onFulfilled函數。可以使用新的 Promise 語法或使用 Promise.resolve(value) 建立 Promise 物件。
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); });
上面程式碼的意思是向testPromise方法傳遞一個參數,該方法傳回一個promise物件。如果參數為true,則呼叫promise物件的resolve()方法,然後將傳遞給它的參數傳遞給後續.then中的第一個函數,結果是輸出「hello world」。如果參數為 false,則呼叫 Promise 物件的reject() 方法,這會觸發 .then 中的第二個函數,導致輸出「NoThanks。」
then 方法可以接受兩個回呼函數作為參數。第一個回呼函數在Promise物件的狀態變成resolved時調用,第二個回呼函數在Promise物件的狀態變成rejected時調用。第二個參數是可選的,可以省略。
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方法的第二個參數,指向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中文網其他相關文章!