- Promise.all可以將多個Promise實例包裝成一個新的Promise實例。
- Promise.all獲得的成功結果的數組裏面的數據順序和發送請求的順序是一致的,而不會根據響應結果的順序排序。
- Promise.all失敗的時候則返回最先被reject失敗狀態的值,與成功的返回順序是不同的。
Promse.all在處理多個異步請求時非常有用,例如表單中上傳相冊,需要所有圖片上傳完畢得到地址才能提交表單,可以通過Promse.all控制一個loading變量的狀態來校驗提交條件。
上傳相冊的例子:
//假設這是已選擇的文件列表
let files = ['aaaa.jpg','bbbb.jpg','cccc.jpg']
//上傳發出的請求列表
let fileRequests = [];
//請求中狀態
let requesting = true;
//循環文件列表上傳
files.forEach(file => {
//定義FormData格式的參數
let formData = new FormData();
formData.append('folder', 'album'); //假設上傳到服務器上指定的album文件夾下
formData.append('file', file);
//axios接收到FormData格式的參數,自動使用Content-Type: multipart/form-data方式上傳
let fileRequest = axios.post('http://www.lihefei.com/upload/file', formData)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
//把上傳請求加入列表
fileRequests.push(fileRequest);
});
//所有請求完成結果
Promise.all(fileRequests).then((response) => {
console.log(response); //所有請求成功結果:['aaaa.jpg上傳成功','bbbb.jpg上傳成功','cccc.jpg上傳成功']
}).catch((error) => {
console.log(error); //所有請求失敗結果
}).then((result) => {
requesting = false; //所有請求結束,更新請求中狀態
})
//提交表單
function submit() {
if (requesting) {
console.log('圖片正在上傳,請稍後提交');
return;
}
}