一 概述html
Promise(承諾)有三種狀態:pending(待定的)、fulfilled(履行)、reject(拒絕)。ios
二 建立Promiseaxios
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <script> let obj = axios.get('/abc'); console.log(obj); // Promise {<pending>} console.log(obj instanceof Promise); // true; </script> </body> </html>
三 執行Promise函數
then方法接受兩個函數做爲參數。onFulfilled是必須的,onRejected是可選的。spa
axios.get('/user?ID=12345') .then(val => { console.log('fulfill函數', val); }, reason => { console.log('reject函數', reason); });
四 捕獲異常code
(1)Promise拒絕時,若是onRejected是個函數,則執行onRejected函數。htm
axios.get('/user?ID=12345') .then(val => { console.log('fulfill函數', val); }, reason => { console.log('reject函數', reason); }) .catch(err => { console.log(err); });
(2)若是onRejected不是函數或者爲空,則JS引擎內部會提供一個函數來做爲onRejected函數,而且這個替代函數會拋出錯誤,從而執行catch部分。對象
axios.get('/user?ID=12345') .then(val => { console.log('fulfill函數', val); }) .catch(err => { console.log('出錯了',err); });
五 返回值blog
then、catch的返回值都是Promise對象,因此能夠進行鏈式調用。ip
let obj = axios.get('/user?ID=12345') .then(val => { console.log('fulfill函數', val); },reason => { console.log('reject', reason); }); setTimeout(()=>{ console.log(obj); },1000);
let obj = axios.get('/user?ID=12345') .then(val => { console.log('fulfill函數', val); }) .catch(err => { console.log('出錯了',err); }); setTimeout(()=>{ console.log(obj); },1000);