vue實現多接口輪詢,並把json打包成json文件且壓縮爲zip包|8月更文挑戰

實際需求

產品小哥哥須要把一堆json文件根據對應的API文件名打包成對應的名稱的json包,而後裝在一塊兒並壓縮成zip格式的壓縮包,下載下來前端

  • 先分解需求
  1. 先根據多個json文件的api,獲取到對應的json文件
  2. 把對應的json文件分門別類的方法,並賦予對應的名稱
  3. json文件解碼並放在一個文件夾下進行zip壓縮
  • 難點
  1. 多個json的api接口同時請求,並須要捕獲哪一個接口請求失敗
  2. json文件裏的中文字符下載到本地時的亂碼問題
  3. jszip和file-saver的使用

這裏須要用到三個技術難點ajax

  1. promise.all: 這個來作多個json的api接口同時請求,並且報錯的時候捕獲
  2. jszip的使用
  3. file-saver的使用

1. Promise.all的使用

Promise.all能夠將多個Promise實例包裝成一個新的Promise實例。同時,成功和失敗返回值是不一樣的,成功的時候返回的是一個結果數組,而失敗的時候返回最早被reject失敗狀態的值算法

示例:npm

let p1 = new Promise((resolve, reject) => {
  resolve('成功了')
})

let p2 = new Promise((resolve, reject) => {
  resolve('success')
})

let p3 = Promse.reject('失敗')

Promise.all([p1, p2]).then((result) => {
  console.log(result)               //['成功了', 'success']
}).catch((error) => {
  console.log(error)
})

Promise.all([p1,p3,p2]).then((result) => {
  console.log(result)
}).catch((error) => {
  console.log(error)      // 失敗了,打出 '失敗'
})
複製代碼

Promse.all在處理多個異步處理時很是有用,好比說一個頁面上須要等兩個或多個ajax的數據回來之後才正常顯示,在此以前只顯示loading圖標。json

須要特別注意的是,Promise.all得到的成功結果的數組裏面的數據順序和Promise.all接收到的數組順序是一致的,即p1的結果在前,即使p1的結果獲取的比p2要晚。這帶來了一個絕大的好處:在前端開發請求數據的過程當中,偶爾會遇到發送多個請求並根據請求順序獲取和使用數據的場景,使用Promise.all毫無疑問能夠解決這個問題。api

實際需求:數組

const a = new Promise((resolve, reject) => {
	api.aDownload(i.id)
	.then(r => resolve(r))
	.catch(e => reject(e))
      }),
      b = new Promise((resolve, reject) => {
	api.bDownload(i.id)
	.then(r => resolve(r))
	.catch(e => reject(e))
      }),
      c = new Promise((resolve, reject) => {
	api.csDownload(i.id)
	.then(r => resolve(r))
	.catch(e => reject(e))
      }),
      d = new Promise((resolve, reject) => {
	api.dDownload(i.id)
	.then(r => resolve(r))
	.catch(e => reject(e))
      }),
      e = new Promise((resolve, reject) => {
	api.cDownload(i.id)
	.then(r => resolve(r))
	.catch(e => reject(e))
      }),
      filename = new Promise((resolve, reject) => {
	api.getFIlename(i.id)
	.then(r => resolve(r))
	.catch(e => reject(e))
      })
Promise.all([a, b, c, d, e, filename]).then(r => {
    console.log(r)   // 成功回調
}).catch(e => {
    console.log(e)   // 失敗回調
})
複製代碼

返回的結果集promise

image.png

(其實這裏第二和第三個接口也是Object類型來的,後來改了,沒切到圖)markdown

2. JSZip和File-saver的使用

npm install JSZip File-saver
# 或者
yarn add JSZip File-saver
複製代碼
  1. 使用jszip先把文件下載到後,進行轉義並保存爲對應名稱的json文件
const zip = new JSZip()
zip.file('a.json', JSON.stringify(a), { binary: false })
複製代碼

image.png

第一個是輸出的名稱app

第二個是內容是須要進行轉義的

image.png

第三個binary: false是是否轉爲二進制碼,若是爲true,那麼就會出現中文亂碼的狀況

image.png

  1. json文件拿到了之後,進行blob壓縮並輸出文件的二進制流,這裏用到jszip的generateASync
zip.generateAsync({
  type: "blob", // 壓縮類型
  compression: "DEFLATE", // 壓縮算法
  compressionOptions: { // 壓縮級別
          level: 9
  }
}).then(res => {
      console.log(res)
}).catch(err => {
      console.log(err)
})
複製代碼
  1. json文件準備好了之後,進行json文件壓縮成zip,而後賦予定義的filename名稱,並下載下來

這裏用到了file-saver的saveAs能力

FileSaver.saveAs(res, 'xxx.zip')
複製代碼

至此,功能實現 完整代碼

import jszip from 'jszip'
import fileSaver from 'file-saver'
const zip = JSZip(),
      FileSaver = fileSaver(),
      a = new Promise((resolve, reject) => {
	api.aDownload(i.id)
	.then(r => resolve(r))
	.catch(e => reject(e))
      }),
      b = new Promise((resolve, reject) => {
	api.bDownload(i.id)
	.then(r => resolve(r))
	.catch(e => reject(e))
      }),
      c = new Promise((resolve, reject) => {
	api.csDownload(i.id)
	.then(r => resolve(r))
	.catch(e => reject(e))
      }),
      d = new Promise((resolve, reject) => {
	api.dDownload(i.id)
	.then(r => resolve(r))
	.catch(e => reject(e))
      }),
      e = new Promise((resolve, reject) => {
	api.cDownload(i.id)
	.then(r => resolve(r))
	.catch(e => reject(e))
      }),
      filename = new Promise((resolve, reject) => {
	api.getFIlename(i.id)
	.then(r => resolve(r))
	.catch(e => reject(e))
      })
Promise.all([a, b, c, d, e, filename]).then(r => {
    zip.file('a.json', JSON.stringify(r[0].data), { binary: false })
    zip.file('b.json', JSON.stringify(r[1].data), { binary: false })
    zip.file('c.json', JSON.stringify(r[2].data), { binary: false })
    zip.file('d.json', JSON.stringify(r[3].data), { binary: false })
    zip.file('e.json', JSON.stringify(r[4].data), { binary: false })
    zip.generateAsync({
      type: "blob", // 壓縮類型
      compression: "DEFLATE", // 壓縮算法
      compressionOptions: { // 壓縮級別
              level: 9
      }
    }).then(res => {
          FileSaver.saveAs(res, `${ r[5].data.file_name }.zip`)
    }).catch(err => {
          console.log(err)
    })
}).catch(e => {
    console.log(e)   // 失敗回調
})
複製代碼

寫碼不易,麻煩給點鼓勵,謝謝

最後最後:

公衆號:小何成長,佛系更文,都是本身曾經踩過的坑或者是學到的東西

有興趣的小夥伴歡迎關注我哦,我是:何小玍。 你們一塊兒進步鴨

相關文章
相關標籤/搜索