在一個函數里面,需要發送多個ajax請求,並且下一個請求都需要上一個請求返回的數據,那我們可以下面的做法:
new Promise((resolve, reject) => { //執行異步請求 $.get("test.cgi", { name: "John", time: "2pm" }, function (data) { resolve(data) }); }).then(data => { console.log('請求成功1') return new Promise(resolve => { $.get("test.cgi", { name: "John", time: "2pm" }, function (data) { resolve(data) }); }).then(resolve => { console.log('請求成功2') }) })
但有時候也不是需要下一個請求要上一個請求的數據,兩個請求各自不相干,但我們要求兩個請求執行完畢后,再拿他們的數據進行統一處理,promise提供了一個all方法能讓我們做到:
Promise.all([ new Promise(resolve => { $.get("test.cgi", { name: "John", time: "2pm" }, function (data) { resolve(data) }) }), new Promise(resolve => { $.get("test.cgi", { name: "John", time: "2pm" }, function (data) { resolve(data) }) }) ]).then(response => { console.log(response[0]) console.log(response[1]) })
all要傳入一個數組,數組的元素是一個 Promise對象,相當封裝一個異步操作;當數組中的所有Promise的異步操作執行完畢,那就會調用then進行處理,參數response包含了所有的promise返回的數據,是一個數組,response[0]表示第一個promise返回的數據,以此類推。