避免回调地狱 [英] Avoiding callback hell
本文介绍了避免回调地狱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码可为"./markdown"文件夹中的每个markdown文件提供服务.在"/api/markdown/文件名"中.
I have this code that serves every markdown file in the './markdown' folder. At '/api/markdown/filename'.
var apiRouter = express.Router();
markdownFolder = './markdown/';
apiRouter.get('/:markdown_file_noext', function(req, res) {
fs.readdir(markdownFolder, function(err, markdown) {
if (err) throw err;
markdown.forEach(function(file) {
fs.readFile(markdownFolder + file, 'utf8', function(err, file_content) {
if (err) throw err;
fileNoExtension = file.slice(0, file.indexOf('.'));
if (req.params.markdown_file_noext == fileNoExtension) {
res.json({
'title': fileNoExtension,
'markdown': marked(file_content)
});
};
});
});
});
});
但是我最终拥有大量的回调来实现'fs'方法的本质.我如何避免这种情况?
But i end having a ton of callbacks do the the nature of the 'fs' methods. How do i avoid this?
推荐答案
使用 查看全文