catalogue
Synchronous asynchronous in Promise
Using Promise to resolve callback hell
Third party then FS solution callback hell
async and await resolve callback hell
4. async and await read JSON file cases
Promise object
An object added in ES6 is mainly used to solve the problem that asynchronous codes cannot return values, so a Promise object is added
// Import fs module import fs from 'fs'; // Create Promise object. The parameter is a function with two formal parameters; // resolve: pass, which is generally used to process data after success; // Reject: reject, which is generally used to process failed data; const p1 = new Promise((resolve, reject) => { // In the function, there must be asynchronous code; fs.readFile('./txt/a.txt', 'utf8', (err, data) => { // Originally, neither our data nor err can be returned to FS through return Readfile(); if (err == null) { // If there is no error, put the read information into fs.com through resolve Readfile(); resolve(data); } else { // If there is an error, put the error in fs.com through reject Readfile(); reject(err); } }) }); p1.then(res => console.log(res)); // p1 stores the values thrown by resolve and reject! // //then() can receive two parameters. The first function is processed successfully and the second function fails; // p1.then(res => { // console.log(res); // }, err => { // console.log(err.message); // }); // p1.then(res => { // console.log(res); // }).catch(err => { // console.log('File read error: '+ err.message); // });
Note:
new Promise()
A function must be passed in as the parameter of Promise. This function will be executed when new Promise is added
The function has two formal parameters: resolve # and reject
Function is equivalent to a container, where asynchronous code can be considered to be put
Pass the successful result of the asynchronous task to the resume function and the failed information to the reject function
p1.then(res => { console.log(res); }, err => { console.log(err.message); }); p1.then(res => { console.log(res); }).catch(err => { console.log('File read error: ' + err.message); }); // perhaps p.then( result => { /* Get successful results*/ } ).catch( err => { /* Get failed results*/ } );
Note:
The then method receives parameters of function type and only handles them successfully
The then method receives parameters of two function types, which are used to receive the value of resolve and the value of reject respectively
The then method can also receive only one parameter, indicating that it only accepts the value of resolve. The failure result can be captured by calling the catch method through chain programming
Synchronous asynchronous in Promise
Like other new objects, new Promise is a synchronization task
The result is obtained asynchronously (when the then method is triggered by a call to resolve)
Using Promise to resolve callback hell
// Import fs module import fs from "fs"; // Create Promise object; const p1 = new Promise((resolve, reject) => { fs.readFile('./txt/a.txt', 'utf8', (err, data) => { resolve(data); // Do not make judgment or consider errors; }); }); const p2 = new Promise((resolve, reject) => { fs.readFile('./txt/b.txt', 'utf8', (err, data) => { resolve(data); // Do not make judgment or consider errors; }); }); const p3 = new Promise((resolve, reject) => { fs.readFile('./txt/c.txt', 'utf8', (err, data) => { resolve(data); // Do not make judgment or consider errors; }); }); // read file const a = p1.then(res => { console.log(res); // The callback function in then() does not write the return value, but returns a blank Promise object by default. If a real Promise object is returned, it will be assigned to then(); return p2; }) const b = a.then(res => { console.log(res); // Return a Promise object and call the next then(); return p3; }) const c = b.then(res => { console.log(res); });
Promise package
// Import fs module import fs from 'fs'; // Encapsulate a method and return a Promise object; function getPromise(url) { return new Promise((resolve, reject) => { fs.readFile(url, 'utf8', (err, data) => { resolve(data); // Do not make judgment or consider errors; }); }); }; // call getPromise('./txt/a.txt').then(res => { console.log(res); return getPromise('./txt/b.txt'); }).then(res => { console.log(res); return getPromise('./txt/c.txt'); }).then(res => { console.log(res); }); // Note: now the conditions are not allowed. We can encapsulate it ourselves. In the future, if the conditions are good, let others encapsulate it, and we can call it!
Third party then FS solution callback hell
// //Ordinary fs module, readFile() returns undefined; // //Then FS module, readFile() returns Promise object; // import fs from 'fs'; // const a = fs.readFile('./txt/a.txt', 'utf8', () => {}); // console.log(a); // //Download: NPM I then FS // import thenFs from 'then-fs'; // const b = thenFs.readFile('./txt/a.txt', 'utf8'); // console.log(b); // Import module import thenFs from 'then-fs'; // read file thenFs.readFile('./txt/a.txt', 'utf8').then(res => { console.log(res); return thenFs.readFile('./txt/b.txt', 'utf8'); }).then(res => { console.log(res); return thenFs.readFile('./txt/c.txt', 'utf8'); }).then(res => { console.log(res); }); // In the future, many third-party modules will support Promise object development;
async and await keywords
Async and await were proposed in ES2017. The appearance of async and await keywords simplifies the use of Promise objects
async keyword
async is used to decorate a function
async modified functions always return a Promise object
All values in the function will be automatically wrapped in the resolved Promise
await keyword
await can only appear in asynchronous functions
await can pause code execution and let the later synchronization code execute first
await is followed by a Promise object
await returns the parameter res in the callback function in then () in the Promise object
async and await resolve callback hell
// Then FS import import thenFs from 'then-fs'; // Define a function decorated with async async function fn() { // Read file information in order const str1 = await thenFs.readFile('./txt/a.txt', 'utf8'); console.log(str1); const str2 = await thenFs.readFile('./txt/b.txt', 'utf8'); console.log(str2); const str3 = await thenFs.readFile('./txt/c.txt', 'utf8'); console.log(str3); } // Functions are not called or executed fn();
4. async and await read JSON file cases
// Four methods of encapsulation: adding, deleting, modifying and checking; Request to return information; // Use: await + async + then FS + ES6 modularization // 0. Import module import fs from 'then-fs'; // 1. Query - prompt: the returned data is put into Promise object! async function getData() { // Read the information / / await must appear in the async decorated function const str = await fs.readFile('./data.json', 'utf8'); return JSON.parse(str); } // //Testing // getData().then(res => { // console.log(res); // }); // 2. Add - returns a Promise object; async function addData(obj) { try { // Take out the value in Promise object; const arr = await getData(); // Adding data to an array obj.id = arr[arr.length - 1].id + 1; arr.push(obj); // write in fs.writeFile('./data.json', JSON.stringify(arr)); return 'Added successfully'; } catch (e) { return 'Add failed'; } } // //Testing // addData({ // "author": "big Liu", // "bookname": "trisomy 2", // "publisher": "Hubei people's Publishing House" // }).then(res => { // console.log(res); // }) // 3. Delete - returns a Promise object; async function delData(id) { try { // Get array const arr = await getData(); // Delete the element id, which is the same as the passed id value // Filter the new array. Only when the passed id value is different from the id value of the element can it be qualified to be put into the new array; const newArr = arr.filter(ele => id != ele.id); // Write file - write new array! fs.writeFile('./data.json', JSON.stringify(newArr)); return 'Deleted successfully'; } catch (e) { return 'Delete failed'; } } // //If the test id does not exist, it will not cause an error! // delData(6).then(res => { // console.log(res); // }); // 4. Modify - return a Promise object; async function updateData(obj) { try { // Get array const arr = await getData(); // Get the index value, delete the element and add the element; const index = arr.findIndex(ele => ele.id == obj.id); arr.splice(index, 1, obj); // write file fs.writeFile('./data.json', JSON.stringify(arr)); // return return 'Modified successfully'; } catch (e) { console.log(e.message); return 'Modification failed'; } } // //Testing // updateData({ // "author": "Liu Cixin", // "bookname": "three body 3 - death eternal life", // "publisher": "Hubei people's Publishing House", // "id": 5 // }).then(res => { // console.log(res); // }); // export export default { getData, addData, delData, updateData }