1.博客详情接口 2.promise
router/blog.js
// 获取博客详情 if (method === 'GET' && req.path ==='/api/blog/detail') { const id = req.query.id const data = getDetail(id) return new SuccessModel(data) }a.json
{ "next": "b.json", "msg": "this is a" }b.sjon
{ "next": "c.json", "msg": "this is b" }c.json
{ "next": null, "msg": "this is c" }回调地狱形式 index.js
const fs = require('fs') const path = require('path') // callback 方式获取一个文件的内容 function getFileContent(fileName, callback) { const fullFileName = path.resolve(__dirname, 'files', fileName) fs.readFile(fullFileName, (err, data) => { if (err) { console.error(err) return } // 回调函数 callback( // 把二进制转换为字符串再转换为js对象格式 JSON.parse(data.toString()) ) }) } // 测试 getFileContent('a.json', aData => { console.log('a data', aData) getFileContent(aData.next, bData => { console.log('b data',bData) getFileContent(bData.next, cData => { console.log('c data', cData) }) }) })控制台
$ node index.js a data { next: 'b.json', msg: 'this is a' } b data { next: 'c.json', msg: 'this is b' } c data { next: null, msg: 'this is c' }promise解决回调地狱
const fs = require('fs') const path = require('path') // callback 方式获取一个文件的内容 function getFileContent(fileName) { const promise = new Promise((resolve, reject) => { const fullFileName = path.resolve(__dirname, 'files', fileName) fs.readFile(fullFileName, (err, data) => { if (err) { reject(err) return } resolve( JSON.parse(data.toString()) ) }) }) return promise } // 测试 getFileContent('a.json').then(aData => { console.log('a data', aData) return getFileContent(aData.next) }).then(bData => { console.log('d Data',bData) return getFileContent(bData.next) }).then(cData => { console.log('c data', cData) })**async await **
const fs = require('fs') const path = require('path') // callback 方式获取一个文件的内容 function getFileContent(fileName) { const fullFileName = path.resolve(__dirname, 'files', fileName) fs.readFile(fullFileName, (err, data) => { if (err) { console.error(err) return } console.log(JSON.parse(data.toString())) }) } // 测试 async function test() { const a = await getFileContent('a.json') const b = await getFileContent('b.json') const c = await getFileContent('c.json') } test() $ node index.js { next: 'b.json', msg: 'this is a' } { next: 'c.json', msg: 'this is b' } { next: null, msg: 'this is c' }