Use promise to encapsulate asynchronous read files
const fs = require('fs')
function read (url) {
return new Promise(((resolve, reject) = > {
fs.readFile(url, 'utf8'.function (err, data) {
if(err) reject(err);
resolve(data)
})
}))
}
read('./index.js').then(function (data) {
console.log(data)
}, function (err) {
console.log(err);
})
Copy the code
Encapsulate async as a promise using promisify in node util
const fs = require('fs')
const util = require('util')
let read = util.promisify(fs.readFile);
read('./index.js'.'utf8').then(function (data) {
console.log(data);
}, function (err) {
console.log(err);
});
Copy the code
Chain operation of Primise
const fs = require('fs')
const util = require('util')
let read = util.promisify(fs.readFile);
read('./index.js'.'utf8').then(function (data) {
return read(data, 'utf8') // Return a promise
}).then(res= > {
console.log(res)
return res; // Returns a concrete value
}).then(data= > {
console.log(data)
}).catch((a)= > {
// If an error is written, the callback will go its own, and not write with a catch
});
Copy the code
async await
- Await can only be followed by promise
- Async always returns a Promise object, so you can use then to process the result
- Async functions can also return a non-promise column such as return ‘Hello world’;
async function f1() {
return 'hello world'
}
console.log(f1()); / / below
f1().then(res= > console.log(res)) // 'helle world'
Copy the code
The most elegant way to write it
const fs = require('fs')
const util = require('util')
let read = util.promisify(fs.readFile);
async function result (url) {
let content1 = await read(url,'utf8'); // This will not be executed down without a result
let content2 = await read(content1,'utf8');
return content2 + 'haha'
}
result(url).then((res) = > console.log(res))
Copy the code
Temporary notes
Buffer (hexadecimal)
1024B (byte) === 1K
1 byte === 8 bits
1 Chinese character (3 bytes)
Parse (json.stringify (obj)), recursive loop this will lose the function // shallow copy: object.assign () slice() […[1,2,3]]
let arr = ['nan'.'fei'.'yan'];
let newArr = arr.slice(0);
arr[0] = 'liguigong';
console.log(newArr);
console.log(arr);
Copy the code
Promise. All applications
async function result () {
let [name, age] = await Promise.all([read('a.txt'.'utf8'),read('b.txt'.'utf8')]);
console.log(name,age)
}
Copy the code