使用前一个promise.all返回的数组链promise.all

时间:2016-03-06 20:56:45

标签: javascript node.js promise

我在节点中编写自己的博客平台。我有一堆代码执行以下操作:

  1. 从一堆文件夹中读取.md个文件,其中每个文件夹都是顶级文件夹。
  2. 处理每个文件中的数据,从YAML前端内容和降价格式的文本中读取数据。
  3. 按日期对这些进行排序,然后写出一堆.json个文件,如下所示:
    • cache/posts.json
    • cache/[category]/[category].json
    • cache/[category]/[post-id].jsoncache/[category]/[post-id].json,..等。
  4. 我使用了一个厄运的回调三角形。有人告诉我,我应该用承诺做到这一点,然而,尽可能地尝试,我只是不能让我的代码工作。所以,我有:

    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

1 个答案:

答案 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);
  });
}