我在节点中编写自己的博客平台。我有一堆代码执行以下操作:
.md
个文件,其中每个文件夹都是顶级文件夹。YAML
前端内容和降价格式的文本中读取数据。.json
个文件,如下所示:
cache/posts.json
cache/[category]/[category].json
cache/[category]/[post-id].json
,cache/[category]/[post-id].json
,..等。我使用了一个厄运的回调三角形。有人告诉我,我应该用承诺做到这一点,然而,尽可能地尝试,我只是不能让我的代码工作。所以,我有:
folders = ['notes','gallery','diary'];
function getFilesInFolder(folder) {
//returns a new Promise that contains an array of markdown files
}
function getFileContents(folder,file) {
//returns a new Promise that contains the data from the file
}
function processPostData(data,folder,file) {
//returns a new Promise that contains a json object that I want to
//write out to a file
}
function processAllPosts() {
Promise.all(folders.map(getFilesInFolder))
.then((files,folder) => {
console.log(files);
})
.catch((err) => {
console.log('yuk, an error:',err);
})
}
我能解决的问题是如何为Promise.all
中返回的文件数组调用新getFilesInFolder
并将其传递给getFileContents
。
我也使用数组map
函数执行此操作,如何传入当前文件夹,例如:files.map(getFileContents(file,folder))
?
任何帮助将不胜感激。感谢。
另外:我现在有了这个代码。对于任何可能觉得有用的人来说,它是here
答案 0 :(得分:1)
这些对我来说似乎是顺序操作,而不是可以并行运行的操作。您将使用Promise.all并行执行一系列异步操作,并等待所有操作在下一个操作之前完成。
我会使用map函数链接您的异步操作,以转换生成的数组:
function processAllPosts() {
return getFilesInFolder.then(function(files){
return Promise.map(files, function(file){
return getFileContents(file)
});
})
.then(function(fileContents)){
return Promise.map(fileContents, function(content){
return processPostData(content);
});
})
.catch(function(err) {
console.log('yuk, an error:',err);
});
}