Promise方法解决回调地狱

一、回调地狱示例

弊端:

  1. data1,data2,data3这三个数据不能重名,调试起来很不方便。
  2. 需要的操作多时,回调会一直往里塌陷。
const fs = require("fs")
fs.readFile("./one.txt", (err, data1) => {
  fs.readFile("./two.txt", (err, data2) => {
    fs.readFile("./three.txt", (err, data3) => {
      console.log(data1 + "\n" + data2 + "\n" + data3)
    })
  })
})

二、使用Promise解决方案

const fs = require("fs")

const p = new Promise((resolve, reject) => {
  fs.readFile("./one.txt", (err, data) => {
    resolve(data)
  })
})
p.then(value => {
  return new Promise((resolve, reject) => {
    fs.readFile("./two.txt", (err, data) => {
      resolve([value, data])
    })
  })
}).then(value => {
  return new Promise((resolve, reject) => {
    fs.readFile("./three.txt", (err, data) => {
      value.push(data)
      resolve(value)
    })
  })
}).then(value => {
  let str = value.join("\n")
  console.log(str)
})

三、使用async、await方法

const fs = require("fs")
function readOne() {
  return new Promise((resolve, reject) => {
    fs.readFile("./one.txt", (err, data) => {
      if (err) {
        reject(err)
      }
      resolve(data)
    })
  })
}
function readTwo() {
  return new Promise((resolve, reject) => {
    fs.readFile("./two.txt", (err, data) => {
      if (err) {
        reject(err)
      }
      resolve(data)
    })
  })
}
function readThree() {
  return new Promise((resolve, reject) => {
    fs.readFile("./three.txt", (err, data) => {
      if (err) {
        reject(err)
      }
      resolve(data)
    })
  })
}

async function test() {
  let one = await readOne()
  let two = await readTwo()
  let three = await readThree()
  console.log(one + '\n' + two + '\n' + three)
}
test()

你可能感兴趣的:(笔记,javascript,前端,node.js)