介紹
Javascript Promise 是一個非常常用的編程模式,主要用於處理非同步代碼。在過去,我們在編寫非同步代碼時會使用回調函數,但是使用回調函數有其自身的一些缺陷,例如代碼可讀性差、嵌套過深等問題。Promise 提供了一種更優雅的方式來解決這些問題。
Promise 的基礎知識
Promise 的定義
在 Javascript 中,Promise 是一個對象,表示非同步操作的最終完成(或失敗)及其結果值。
Promise 的狀態
Promise 有三種狀態:Pending、Fulfilled 和 Rejected。
- Pending(進行中):Promise 的初始狀態,即非同步操作還沒有完成。
- Fulfilled(已成功):非同步操作已經完成,並且成功執行。
- Rejected(已失敗):非同步操作已經完成,並且執行失敗。
創建一個 Promise
可以使用 Promise 構造函數來創建一個 Promise。
const promise = new Promise(function(resolve, reject) {
// 非同步操作
if(非同步操作成功) {
resolve('結果');
} else {
reject('錯誤');
}
});
Promise 的鏈式調用
Promise 支持鏈式調用,這種編程模式被稱為 Promise 鏈式調用。
promise.then(function(result) {
// 處理成功結果
return result;
}).catch(function(error) {
// 處理失敗結果
return error;
}).finally(function() {
// 無論成功或失敗均可執行的函數
});
Promise 的進階
Promise.all()
Promise.all() 方法將多個 Promise 實例包裝成一個 Promise 實例。
當所有的 Promise 實例都返回結果時,Promise.all() 返回一個由所有 Promise 實例返回結果組成的數組。
當 Promise 實例中有一個 Promise 實例返回失敗時,Promise.all() 直接返回失敗結果。
Promise.all([promise1, promise2, promise3]).then(function(results) {
// results 為數組,包含了所有 Promise 實例返回的結果值
}).catch(function(error) {
// 任意一個 Promise 實例返回失敗,就會執行 catch 方法
});
Promise.race()
Promise.race() 方法與 Promise.all() 方法類似,不同之處在於它只需要等待所有 Promise 實例中最快的返回結果,並返回該結果。
Promise.race([promise1, promise2, promise3]).then(function(result) {
// result 為最快返回的 Promise 實例的結果值
}).catch(function(error) {
// 任意一個 Promise 實例返回失敗,就會執行 catch 方法
});
Promise 的應用場景
Ajax 非同步請求數據
Promise 最經典的應用場景之一就是 Ajax 非同步請求數據。
function getData(url) {
return new Promise(function(resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if (xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(xhr.statusText);
}
};
xhr.onerror = function() {
reject('網路錯誤');
};
xhr.send();
});
}
// 使用方式
getData('http://example.com/data.json').then(function(data) {
console.log(data);
}).catch(function(error) {
console.error(error);
});
延遲執行代碼
Promise 還可以用於延遲執行代碼(類似於 setTimeout() 函數)。
function delay(time) {
return new Promise(function(resolve) {
setTimeout(resolve, time);
});
}
// 使用方式
delay(1000).then(function() {
console.log('1s 後執行');
});
獲取多個非同步操作結果
使用 Promise.all() 方法可以獲取多個非同步操作的結果。
const promise1 = new Promise(function(resolve) {
setTimeout(function() {
resolve('結果 1');
}, 1000);
});
const promise2 = new Promise(function(resolve) {
setTimeout(function() {
resolve('結果 2');
}, 2000);
});
const promise3 = new Promise(function(resolve) {
setTimeout(function() {
resolve('結果 3');
}, 3000);
});
Promise.all([promise1, promise2, promise3]).then(function(results) {
console.log(results); // ['結果 1', '結果 2', '結果 3']
});
總結
本篇文章從 Promise 的基礎知識、進階應用以及應用場景三個方面對 Promise 做了詳細闡述。通過本篇文章的學習,我們可以更加深入地理解 Promise 的內在機制,並靈活應用 Promise 編程模式來處理各種非同步代碼。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/309022.html