Firebase云功能:Promise.all问题(承诺)

时间:2018-12-15 20:36:51

标签: javascript firebase promise

我循环抛出Firebase存储中的文件列表,我想在循环时修改字符串,

这是我尝试做的事情:

 var str;

 storage.bucket().file(...).download((err, content) => {
    str=content.toString();

    storage.bucket().getFiles(...).then(results => {
        const files = results[0];
        var promise = new Promise(function(resolve,reject){
           files.forEach(file => {
               ...
               str=str.replace("t","a");
           });
           resolve(str);
      });

      Promise.all(promise).then(function(str) {
        console.log(str); //NOT OKAY, the value is still "test" 

        file.save(str, function(err) { ... });
     });

我也尝试过:

  

promise.then(function(result){

但结果相同:(

更新: 我已经编辑了上面的代码,但仍然无法正常工作:

enter image description here

有什么主意吗?

更新2:

enter image description here

它仍然不起作用:(

2 个答案:

答案 0 :(得分:0)

如果对某人有用,这是我找到的解决方案:

var promises = [];
var str="string containing data to replace with signed url";

storage.bucket().getFiles({ prefix: folderPath }).then(results => {
  const files = results[0];
  files.forEach(function(file) {

     promises.push( //the trick was here

       file.getSignedUrl(signedUrlConfig).then(signedUrls => {
         ...
         surl = signedUrls[0];
         str=str.replace("a",surl); //eg: replace with signed url.
         return str;
       });
     );
  });
  Promise.all(promises).then(() => {
    console.log(str); //str contains all signed url
  });
});

答案 1 :(得分:-1)

似乎您正在寻找

const promise = storage.bucket().file().download().then(str => {
//    ^^^^^^^^^                                   ^^^^^
    return storage.bucket().getFiles().then(results => {
//  ^^^^^^
        const files = results[0];
        for (const file of files) {
            …
            str = str.replace("t","a");
        }
        return str;
    //  ^^^^^^
    });
});

promise.then(str => { /*
^^^^^^^^^^^^ */
    console.log(str);
    return file.save(str); // should return a promise
});

这里既不需要new Promise也不需要Promise.all。您可能会使用后者来删除嵌套,甚至可能同时运行getFiles()download(),请参阅How do I access previous promise results in a .then() chain?