JavaScript 中的异步编程
需要:将两次读取的文件最后合并一起
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论