链接多个承诺,包括Promise.all

kay*_*asa 5 angularjs jszip ionic-framework cordova-plugins angular-promise

我有一个要求链接Promises的要求.在我的Ionic应用程序中,我需要迭代一个文件列表并压缩它们.然后拉链需要存储在设备本身(在这种情况下为iPhone).

我已经有了需要在数组中压缩的文件列表.所以,我正在迭代它们并使用$ cordovaFile获取这些文件的binay内容.然后我将二进制文件添加到JSZip对象.最终结果应该是将所有文件的二进制内容添加到zip.file中,以便生成zip文件.

//wrapping in Promise.all so that we don't proceed until we have the content of all files added to zip
var zip = new JSZip();
return Promise.all(
        filesList.forEach(function(file) {
           console.log('file to be added using $cordovaFile '+file); 
           // Getting the content of each file using $cordovaFile. This returns a promise. 
                  return $cordovaFile.readAsBinaryString(cordova.file.dataDirectory + $rootScope.username, file)
                       .then(function(binaryData) {
                        return new Promise(function(resolve, reject) {
                         //Adding content of all files to zip.file so that it can be zipped in the next step.
                            resolve(zip.file(file, binaryData, {binary: true}));
                        })        
                      })
                      .catch(function(error) {
                        console.log('Error during fetch content or zipping '+JSON.stringify(error));
                      })
                 })
             )
Run Code Online (Sandbox Code Playgroud)

一旦zip.file拥有所有内容,我在JSZip中调用另一个生成zip的函数.这也会返回一个承诺,所以我需要链接到$ cordovaFile.writeFile,以便zip可以在本地编写.$ cordovaFile.writeFile还返回一个Promise,这将是链中的最后一个承诺.

.then(function(zipData) {
// async request to generate the zip
                return zipData.generateAsync({type:"blob"});
            }).then(function (blob) {
  // once we have the zip, save it to the device 
                $cordovaFile.writeFile(cordova.file.dataDirectory+$rootScope.username, 'abc.zip', blob, true)
                .then(function(data) {
                   console.log('Zip file written to device at '+cordova.file.dataDirectory+$rootScope.username); 
                })
            }).catch(function(error) {
                console.log('Error while zipping and writing '+JSON.stringify(error));
            })  
Run Code Online (Sandbox Code Playgroud)

这就是完整代码的样子

var zipFiles = function(filesList) {
var zip = new JSZip();

             return Promise.all(
                filesList.forEach(function(file) {
                   return $cordovaFile.readAsBinaryString(cordova.file.dataDirectory + $rootScope.username, file)
                      .then(function(binaryData) {
                        return new Promise(function(resolve, reject) {
                            resolve(zip.file(file, binaryData, {binary: true}));
                        })        
                      })
                      .catch(function(error) {
                        console.log('Error during fetch content or zipping '+JSON.stringify(error));
                      })
                 })
             )
            .then(function(zipData) {
                return zipData.generateAsync({type:"blob"});
            }).then(function (blob) {
                $cordovaFile.writeFile(cordova.file.dataDirectory+$rootScope.username, 'abc.zip', blob, true)
                .then(function(data) {
                   console.log('Zip file written to device at '+cordova.file.dataDirectory+$rootScope.username); 
                })
            }).catch(function(error) {
                console.log('Error while zipping and writing '+JSON.stringify(error));
            }) 
} 
Run Code Online (Sandbox Code Playgroud)

挑战是在Promise.all完成后,没有任何东西被执行.因此,没有任何开始'然后(函数(zipData)'被执行.

我觉得这与我链接Promise的方式有关.任何帮助将受到高度赞赏.

Geo*_*-it 1

这是因为forEach返回undefined,所以Promise.all立即解决。你应该将其更改为.map.

此外,请记住,你的zipData论点不会是你所期望的。该 Promise 的参数将包含从 . 返回的每个结果zip.file(file, binaryData, {binary: true})

在这种情况下,您不需要zipData. 该zip变量将完成这项工作。在下面的代码中,我还通过删除循环中的冗余承诺并在.then外部取出一个来简化承诺链。

var zipFiles = function (filesList) {
    var zip = new JSZip();

    var zipFilesPromises = filesList.map(function (file) {
        return $cordovaFile.readAsBinaryString(cordova.file.dataDirectory + $rootScope.username, file)
            .then(function (binaryData) {
                return zip.file(file, binaryData, { binary: true });
            });
    }); 

    return Promise.all(zipFilesPromises)
        .then(function () {
            return zip.generateAsync({ type: "blob" });
        })
        .then(function (blob) {
            return $cordovaFile.writeFile(cordova.file.dataDirectory + $rootScope.username, 'abc.zip', blob, true);
        })
        .then(function (data) {
            console.log('Zip file written to device at ' + cordova.file.dataDirectory + $rootScope.username);
        })
        .catch(function (error) {
            console.log('Error while zipping and writing ' + JSON.stringify(error));
        })
} 
Run Code Online (Sandbox Code Playgroud)