Actual demand
The product brother needs to package a bunch of JSON files into json packages with corresponding names according to the corresponding API names, and then put them together and compress them into zip packages and download them
- Break down requirements first
- Obtain the corresponding JSON files according to the APIS of multiple JSON files
- A method to categorize the corresponding JSON file and give it the corresponding name
- Json files are decoded and placed in a folder for zip compression
- The difficulties in
- Multiple JSON API interfaces are requested at the same time and need to catch which interface request failed
- Chinese characters in the JSON file are garbled when downloaded to the local PC
- Use of jszip and file-Saver
There are three technical difficulties
- Promise. all: This is used to make multiple JSON API requests at the same time, and an error is captured
- The use of jszip
- The use of file – saver
1. Use of promise. all
Promise.all can wrap multiple Promise instances into a new Promise instance. Also, success and failure return different values, with success returning an array of results and failure returning the first rejected state
Example:
Let p1 = new Promise((resolve, reject) => {resolve(' resolve ')}) let p2 = new Promise((resolve, reject)) Reject) => {resolve('success')}) let p3 = promse.reject (' failure ') Promise. (p2). Then (result) = > {the console. The log (result) / / [' success ', 'success'] }).catch((error) => { console.log(error) }) Promise.all([p1,p3,p2]).then((result) => { console.log(result) }). The catch ((error) = > {the console. The log (error) / / failed, hit 'failure'})Copy the code
Promse.all is useful when dealing with multiple asynchronous processes, such as a page that needs to wait for two or more Ajax data returns before displaying only the Loading icon.
In particular, the order of the data in the array of the successful results obtained by Promise.all is the same as that received by Promise.all, that is, the result of P1 is first, even though the result of P1 is obtained later than p2. This has one great benefit: When developing request data on the front end, there are occasional scenarios where multiple requests are sent and the data is retrieved and consumed according to the order in which they are requested, using Promise.all is a surefire way to solve this problem.
Actual demand:
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, Then (r => {console.log(r) // successful callback}). Catch (e => {console.log(e) // failed callback}).Copy the code
The result set returned
(In fact, the second and third interfaces are also Object types, but later changed, not cut to the graph)
2. Use of JSZip and file-Saver
NPM install JSZip file-saver # or yarn add JSZip file-saverCopy the code
- After downloading the file using jszip, escape it and save it as a JSON file with the corresponding name
const zip = new JSZip()
zip.file('a.json', JSON.stringify(a), { binary: false })
Copy the code
The first is the name of the output
The second is that the content needs to be escaped
The third binary: false is whether to convert to binary, if true, then garbled characters will appear
- Once the JSON file is in the file, compress the bloB and output the binary stream of the file, using Jszip’s generateASync
GenerateAsync ({type: "blob", // compression type: "DEFLATE", // compression algorithm: compressionOptions: {// Compression level: 9 } }).then(res => { console.log(res) }).catch(err => { console.log(err) })Copy the code
- After the JSON file is ready, compress the JSON file into a ZIP file, give the defined filename name, and download it
You use file-Saver’s saveAs capability here
FileSaver.saveAs(res, 'xxx.zip')
Copy the code
At this point, the function to achieve the complete code
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 type: "DEFLATE", // compression algorithm: compressionOptions: {// Compression level: 9 } }).then(res => { FileSaver.saveAs(res, ` ${r [5]. Data. File_name}. Zip `)}). The catch (err = > {the console. The log (err)})}). The catch (e = > {the console. The log (e) / / failure callback})Copy the code
Write code is not easy, trouble to encourage, thank you
Finally, finally:
Public number: small he growth, the Buddha department more text, are their own once stepped on the pit or is learned things
Interested little partners welcome to pay attention to me oh, I was: he Small Life. Everybody progress duck together