Callback hell callback region
When we write code to synchronize time-consuming way, it will clog JS single-threaded, causing the CPU has been waiting for IO to complete before going to execute the code behind.
The execution speed of the CPU is much larger than the hard disk IO speed, so that the wait will only result in a waste of resources.
Asynchronous IO is to solve this problem, can not let the asynchronous CPU idle as much as possible, it will not be completed in that waiting for IO; but is passed to the bottom of the event loop a function of their own to execute the following code. Once the disk IO is completed, the function will be executed as a notification.
Although asynchronous and callback programming method can make full use of CPU, but when the code logic becomes more complex, new problems have emerged - Callback callback geographical Hell!
Function Code
Achieve the following functions:
- Determine a file is a file or directory;
- If it is a directory, read files in this directory, find the end of a txt file;
- Get these txt file size.
Asynchronously
function withoutPromise() {
let target = "test";
fs.stat(target, (err, stat)=>{
if(err){
throw err;
}
// 如果是文件夹
if(stat.isDirectory()){
fs.readdir(target, (err, files)=>{
// 遍历files
files.forEach( f =>{
if(path.extname(f) === '.txt'){
fs.stat(path.join(target, f), (err, stat)=>{
console.log(f+ " : "+stat.size);
});
}
} );
});
}
});
}
Promise way
async function withPromise() {
let target = "test";
//将fs.stat转为一个可以返回Promise对象的方法
let pstat = util.promisify(fs.stat);
let stat = await pstat(target);
// 如果是文件夹
if(stat.isDirectory()){
//将fs.readdir转为一个可以返回Promise对象的方法
let preaddir = util.promisify(fs.readdir)
let files = await preaddir(target)
files.forEach( async (f) => {
if(path.extname(f) === '.txt'){
let stat = await pstat(path.join(target, f));
console.log(stat.size);
}
});
}
}
Promise和async/await
Promise
And async/await
that is to solve the Callback hell of a problem.
promise
promise
The role is an asynchronous callback code packaged, the original of a callback function callback function is split into two, so that the benefits are more readable. The syntax is as follows:
// 创建promise对象
let promise = new Promise((resolve, reject)=>{
// 在异步操作成功的情况选调用resolve,失败的时候调用reject
fs.readFile('xxx.txt',(err, data)=>{
if(err){
reject(err)
}else {
resolve(data.toString())
}
})
});
// 使用promise
promise.then((text)=>{
//then方法是当Promise内部调用了resolve的时候执行
}).catch((err)=>{
//catch方法是当Promise内部调用了reject的时候执行
console.log(err);
})
- Syntax Note: internal Promise resolve and reject method can only be called once, you can not call this a call that; if the call is invalid.
async/await
async/await
The direct effect is the Promise asynchronous code into a synchronized writing, note that the code still is asynchronous .
Syntax requirements:
await
It can only be used in theasync
modified approach, but there isasync
not necessarily requiredawait
.await
With only behindasync
and methodspromise
.
Assuming that the object has a promise, now use the async / await write:
async function asyncDemo() {
try {
// 当promise的then方法执行的时候
let text = await promise
// 当你用promise包装了所有的异步回调代码后,就可以一直await,真正意义实现了以同步的方式写异步代码
console.log('异步道明执行');
}catch (e){
// 捕获到promise的catch方法的异常
console.log(e);
}
}
asyncDemo()
console.log('我是同步代码');
Ultimate writing asynchronous code
- Use first
promise
package asynchronous callback code, node may be used to provideutil.promisify
a method; - Use
async/await
writing asynchronous code.
reference
-
Dark Horse programmer Vincent stack 120 block chain to develop open-source tutorials
https://github.com/itheima1/BlockChain
Learning Videos
Some video synchronized corresponding to the learning station B, press the B station identification to access some home viewing.