JavaScript 中的异步编程

发布于 2022-09-16 15:29:11 字数 1619 浏览 131 评论 0

需要:将两次读取的文件最后合并一起

let result = {}
fs.readFile('./data.json', 'utf8', (err, data) => {
  result.name = JSON.parse(data).name
  fs.readFile('./user.json', 'utf8', (err, data) => {
    result.age = JSON.parse(data).age
    console.log(result)
  })
})

异步回调嵌套的问题,会导致代码难以维护,而且不方便处理错误

let result = {}
function checkValue () {
  if (Object.keys(result).length === 2) {
    console.log(result)
  }
}
fs.readFile('./data.json', 'utf8', (err, data) => {
  result.name = JSON.parse(data).name
  checkValue()
})
fs.readFile('./user.json', 'utf8', (err, data) => {
  result.age = JSON.parse(data).age
  checkValue()
})

多个异步同时执行,在某一时刻拿到最终结果

let result = {}
function after (times, callback) {
  return function (params) {
    if (--times === 0) {
      callback()
    }
  }
}

let checkValue = after(2, function (params) {
  console.log(result)
})

fs.readFile('./data.json', 'utf8', (err, data) => {
  result.name = JSON.parse(data).name
  checkValue()
})
fs.readFile('./user.json', 'utf8', (err, data) => {
  result.age = JSON.parse(data).age
  checkValue()
})

高阶函数处理

const fs = require('fs')

const result = {}
let Dep = {
  arr: [],
  on (fn) {
    this.arr.push(fn)
  },
  emit () {
    if (Object.keys(result).length === 2) {
      this.arr.forEach(fn => fn())
    }
  }
}

Dep.on(function () {
  console.log(result)
})

fs.readFile('./data.json', 'utf8', (err, data) => {
  result.name = JSON.parse(data).name
  Dep.emit()
})
fs.readFile('./user.json', 'utf8', (err, data) => {
  result.age = JSON.parse(data).age
  Dep.emit()
})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

东京女

暂无简介

文章
评论
27 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文