链promise.all从以前的promise.all返回的数组
我正在编写我自己的博客平台。 我有一堆代码,执行以下操作:
- 从一堆文件夹中读取
.md
文件,其中每个文件夹都是顶级类别。 - 处理每个文件中的数据,从
YAML
前端和降格格式的文本中读取数据。 - 按datesorting,然后写一堆
.json
文件,如下所示:-
cache/posts.json
-
cache/[category]/[category].json
-
cache/[category]/[post-id].json
,cache/[category]/[post-id].json
,..等等。
-
我有这个工作与厄运的callback三angular。 有人告诉我,我应该用承诺来做到这一点,然而,尽我所能,我不能让我的代码工作。 所以,我有:
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))
?
任何帮助,将不胜感激。 谢谢。
另外:我现在有这个代码工作。 对于任何可能发现它有用的人来说,都在这里
这些对我来说似乎是连续的行为,而不是可以并行运行的行为。 您可以使用Promise.all来并行执行一系列asynchronous操作,并在下一个操作之前等待所有操作完成。
我会链接你的asynchronous动作,使用地图函数来转换生成的数组:
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); }); }