返回承诺的循环库-同步

时间:2020-08-04 13:22:39

标签: javascript node.js asynchronous promise synchronization

我在这段代码上抓了个头:我阅读了文件夹内容,通过庞然大物转换(返回一个Promise)循环接收到的文件,然后创建了一个我想渲染的对象。 我已经尝试过使用async和promises,但从未能够使其同步。你能请教吗?

fs.readdir('Documents', function (err, files) {
    files.forEach(function (file) {      
      mammoth.convertToHtml({path: "Documents/"+file},options)
      .then(function(result){
          var html = result.value; // The generated HTML
          var messages = result.messages; // Any messages, such as warnings during conversion
          docContent.push({
            "skillName" : file,
            "skillData" : html
          })
      }).done()
   });
});

res.render("index",{docContent:docContent});

1 个答案:

答案 0 :(得分:0)

我也很难理解承诺的收集结果的概念^^;。
我认为记住Promise.all()可以收集Promise的结果是一个很好的起点。

请在下面尝试。

    fs.readdir('Documents', function (err, files) {
        // convertingJob = [Promise, Promise,...]  
        const convertingJob = files.map(function(file) {  
            // just return promise and it will make above convertingJob array 
            return mammoth.convertToHtml({path: "Documents/"+file},options) 
                  .then(function(result){
                        var html = result.value; // The generated HTML
                        var messages = result.messages; // Any messages, such as warnings during conversion
                        // docContent.push({
                        //     "skillName" : file,
                        //     "skillData" : html
                        // })
                        return {
                            "skillName" : file,
                            "skillData" : html
                        }
                   })
                   // .done() // I'm not sure this is necessary
         });

         Promise.all(convertingJob) // Gather(wait) all Promise results!
         .then(jobResults => {      // jobResults would be array of objects returned by mammoth 
            res.render("index",{docContent:jobResults});
         })
    });