使用函数链接承诺

Using a function for chaining promises

我有两个功能,一个是获取内容,一个是保存内容。内容不同,我需要执行不同的任务。我事先知道是什么类型的内容,这两个只是辅助功能。

我正在使用 asyncfuncA().then(asyncFuncB).then(...);但我想我可以使用链接 A 和 B 的函数并像 asyncfuncAB.then(...) 一样使用它,但我遇到了问题。下面的简化代码解释了我想做什么。

     function getCont(url) {
        return new Promise(function (resolve ,reject) {
      // The real code makes request and resolves to response body or rejects with error
     resolve("response body");
        });
     }

     function saveFile  (path,data) {
       return new Promise(function (resolve ,reject) {
     // The real code writes file and resolves to true for success or rejects for error
     resolve(true);
        });
      }

     saveCont("some://url","/some/path").then ( function() {
      // Do some thing for one type of content 
     });

     saveCont("another://url","/another/path").then ( function() {
     // Do another thing for another type of content
     });


    function saveCont(url,path) {
         getCont(url)
         .then(function(content) {
         saveFile(path,data) })
        .then( function() {
         // **  What to put here ??

         });
     };

你不必在最后放任何东西,你只需要 return Promise 对象:

function saveCont(url,path) {
     return getCont(url)     //CHANGED
     .then(function(content) {
        return saveFile(path,data);   // if you do not put a return here, saveFile would still work, but the next step in chain would not wait till SaveFile finishes processing. 
     });
 };