promise advantages

By reading in three different ways file folder files lead to processing advantages when compared with asynchronous callback promise, files folder has three files a.json, b.json, c.json.

// a.json
{
  "content": "this is a.json",
  "next": "b.json"
}
// b.json
{
  "content": "this is b.json",
  "next": "c.json"
}
// c.json
{
  "content": "this is c.json",
  "next": null
}

Now turn to read these three documents, and b.json filename to get through the next a.json file attributes, c.json To obtain the file name of the file name b.json.

First, let's look at the format of the output file contents when reading

const fs = require('fs')
const path = require('path')

// 回调函数且不封装为函数的方式
  const fullFileName = path.resolve(__dirname, 'files', 'a.json')
  fs.readFile(fullFileName, (err, data) => {
    console.log(data)
  })

Read from the file directly out of the binary form

data in binary form

data in binary form

data is converted to a string

console.log(data.toString());

data is converted to a string

data into an object

console.log(JSON.parse(data.toString());

data into an object

Now we use the wording that best meet people's way of thinking to once read the contents of the three documents.

// 回调函数且不封装为函数的方式
const fullFileName = path.resolve(__dirname, 'files', 'a.json')
// 读取a.json
fs.readFile(fullFileName, (err, data) => {
  console.log(JSON.parse(data.toString()))
  const fileName = JSON.parse(data.toString()).next
  const fullFileName = path.resolve(__dirname, 'files', fileName)
  // 从a.json中获得b.json文件名,然后读取b.json
  fs.readFile(fullFileName, (err, data) => {
    console.log(JSON.parse(data.toString()))
    const fileName = JSON.parse(data.toString()).next
    const fullFileName = path.resolve(__dirname, 'files', fileName)
    // 从b.json中获取c.json文件名,然后读取c.json
    fs.readFile(fullFileName, (err, data) => {
      console.log(JSON.parse(data.toString()))
    })
  })
})

Read the results:

promise Example 1

Write the above code reusability is very low, we can consider the contents of the package will read the file to a function, so that every time a direct call that function when reading the contents of a file on it.

// 将读取文件内容封装成一个函数
function readFileContent(fileName) {
  fs.readFile(fileName, (err, data) => {
    console.log(JSON.parse(data.toString()))
  })
}
// 读取a.json的内容
const fullFileName = path.resolve(__dirname, 'files', 'a.json')
readFileContent(fullFileName)

Read the results:

promise Example 2

If we want to complete three consecutive reads the file, and the file name of the next file from a file, the package above function is clearly not meet the requirements.

The above content is a callback function console.log(JSON.parse(data.toString())), so write clearly not dead and then read the next file, if we will be readFileContentthe second parameter into a function, and then calls execute in the callback function, then this function we can again read the next file.

// 封装连续读取文件的函数
function readFileContent(fileName, callback) {
  const fullFileName = path.resolve(__dirname, 'files', fileName)
  fs.readFile(fullFileName, (err, data) => {
    // 这里使用callback时需要传递一个参数,那么定义的callback函数也有一个参数
    callback(JSON.parse(data.toString()))
  })
}

const fileName = 'a.json'
readFileContent(fileName, aData => {
  console.log(aData);
  // 获取b.json的名称
  const fileName = aData.next;
  // 读取b.json
  readFileContent(fileName, bData => {
    console.log(bData)
    // 获取c.json的名称
    const fileName = bData.next
    // 读取c.json
    readFileContent(fileName, cData => {
      console.log(cData)
    })
  })
})

If you like to write a file to be read above continue to increase, then the callback function would have been to increase it, it assumes the shape of a pyramid, with intermediate functions nested function, resulting in lower code readability, which is often said callback hell .

About callback hell recommend this blog, said very clearly, callback hell .

The solution callback hell a more common is the use of promise, knowledge about the promise here is not to say, now use the promise to read the contents of a file.

const promise = new Promise((resolve, reject) => {
  const fullFileName = path.resolve(__dirname, 'files', 'a.json');
  fs.readFile(fullFileName, (err, data) => {
    if (err) {
      reject(err)
    } else {
      resolve(data)
    }
  })
})

promise.then((data) => {
  console.log(JSON.parse(data.toString()))
}, (err) => {
  console.log(err)
})

Reading results

promise Example 2

Obviously can not write complete read multiple files, we now consider to be packaged as a function, if the function returns a promise to make this so called once on a promise to return, so that you can read the file multiple times.

// 封装函数利用promise读取三个文件的内容
function readFileContent(fileName) {
  const fullFileName = path.resolve(__dirname, 'files', fileName)
  return new Promise((resolve, reject) => {
    fs.readFile(fullFileName, (err, data) => {
      if (err) {
        reject(err)
      } else {
        resolve(data)
      }
    })
  })
}

const fileName = 'a.json'
readFileContent(fileName).then((data) => {
  console.log(JSON.parse(data.toString()));
  const fileName = JSON.parse(data.toString()).next;
  return readFileContent(fileName)
}).then((data) => {
  console.log(JSON.parse(data.toString()));
  const fileName = JSON.parse(data.toString()).next;
  return readFileContent(fileName)
}).then((data) => {
  console.log(JSON.parse(data.toString()));
}) 

Read the results:

promise Example 4

Focus codes, line 19 and line 23, when return a new promise in then, the next then the data is the new promise in Resolve (data) of the parameter data, then the response is that this new promise .

When using the promise can be seen, the case of nested function will not occur again, then each is an asynchronous operation, coherent relatively clear, therefore promise but also as a way to solve the more common callback hell, hell to solve the callback more ways to refer to the above recommended thing I read blog.

Finished, if impropriety, but also hope to inform, thanks.

Guess you like

Origin www.cnblogs.com/zhangguicheng/p/12608301.html