Asynchronous understand Nodejs

During the execution of the code, each encounter an asynchronous function, this will put an asynchronous queue asynchronous function, only when the synchronization thread execution after the end of the queue will start to perform asynchronous functions
common asynchronous function: readFile ( ), timers, event

Asynchronous read the file

var fs = require('fs')
console.log('文件开始读取')
fs.readFile('a.txt','utf8', (err, data) => {
    console.log(data)
})
console.log('文件读取结束')
The output is
文件开始读取
文件读取结束
aaaaaa

Here Insert Picture Description

setTimeout(function(){
    console.log(1)
},0);
console.log('2')
The results are

2
. 1
performed after the waiting time while the timer is set to 0, the function of which will be placed in a job queue, waits for executing the code behind

When performing file operations: sequentially read such file A, B files, C files

const fs = require('fs')
const path = require('path')
let a_path = path.join(__dirname, 'file', 'a.txt')
let b_path = path.join(__dirname, 'file', 'b.txt')
let c_path = path.join(__dirname, 'file', 'c.txt')

fs.readFile(a_path, 'utf8', (err, data) => {
    if (err) throw err
    console.log(data)
    fs.readFile(b_path, 'utf8', (err, data) => {
        if (err) throw err
        console.log(data)
        fs.readFile(c_path, 'utf8', (err, data) => {
            if (err) throw err
            console.log(data)

        })
    })
})

When you are finished using the callback function will find a form ** callback hell ** (nested layers, poor readability)
solutions callback hell: Promise:
promise: commitment to the future implementation of
promise has two parameters:

  1. resolve: steering complete unfinished
  2. reject: Unfinished steering failure
const fs = require('fs')
function p1(){
    return new Promise((resolve,reject)=>{
        fs.readFile('1.txt','utf8',(err,data)=>{
             resolve(data)
        })
    })
}
function p2(){
    return new Promise((resolve,reject)=>{
        fs.readFile('2.txt','utf8',(err,data)=>{
              resolve(data)
        })
    })
}
function p3(){
    return new Promise((resolve,reject)=>{
        fs.readFile('3.txt','utf8',(err,data)=>{
             resolve(data)
        })
    })
}
p1().then(result=>{
    console.log(result)
    return p2()
}).then(result=>{
    console.log(result)
    return p3()
}).then(result=>{
    console.log(result)
    return p2()
})

The repeated code encapsulated into a function, called directly when necessary, so it looks clear code logic is not much more nesting levels
callback function is called when the then () method calls the current state of the instance changes. It returns a new instance of Promise

Released three original articles · won praise 0 · Views 40

Guess you like

Origin blog.csdn.net/weixin_45740068/article/details/104801642