外部承诺需要等待内部嵌套的承诺

德文·阿卢瓦利亚(Deven Ahluwalia)

我有这个用例,其中我想做以下事情:

  1. 在indexDb中设置元数据
  2. 遍历一系列图像
  3. 查看img是否已在indexDb中设置
  4. 如果是,则不执行任何操作;否则,请下载img
  5. 在indexDb中设置下载的img(作为blob)
  6. 最后引发所有已处理图像的事件

广告数据:

[{
ETag:"",
S3URL:"",
duration:30,
filename:"",
linear-gradient:"",
status:"",
timerRequired:"yes"
}]

我目前的代码:

 this.Tvlocalforage.setItem('meta', newMeta).then(() => { //Step 1
      for (let idx in ads) { //Step 2
        this.localforage.getItem(ads[idx]['filename']).then(blob => {
           if(!blob){ //Step 3
             LSPromise = imgSrcToBlob(ads[idx]['S3URL'], undefined, 'Anonymous', 1).then((blob) => { //Step 4
              return this.localforage.setItem(ads[idx]['filename'], blob); //Step 5
            });
            LSPromises.push(LSPromise);
           }
        });
      }  
    }).then(() => { 
      if(LSPromises.length) {
        Promise.all(LSPromises).then((data) => {
          this.TvLSkeyCount = LSPromises.length;
          this.fireLoadAssetsEvent(); //Step 6
        });
      } 
    });

我面临的问题:

在解决了设置元数据的承诺后,它立即变为then(),此时LSPromisesnull当然,我了解到内部嵌套的承诺尚未解决。

我尝试的解决方案:

返回LSGetter承诺并稍后下载图像。这也不起作用。

我试过的代码:

this.Tvlocalforage.setItem('meta', newMeta).then(() => { 
      for (let idx in ads) {
        let p = this.Tvlocalforage.getItem(ads[idx]['filename']);
        LSPromises.push({'promise' : p, 'filename' : ads[idx]['filename'], 'url' : ads[idx]['S3URL']});
      }
  }).then(() => { 
    if(LSPromises.length){
      Promise.all(LSPromises.map(obj => {
        obj['promise'].then(blob => {
          if(!blob){
              imgSrcToBlob(obj['url'], undefined, 'Anonymous', 1).resolve(blob => {
                return this.Tvlocalforage.setItem(obj['filename'], blob);
            });   
          }
        });
      })).then((data) => {this.fireLoadAssetsEvent();});
    }

我尝试了2种以上的方法来打包,并尝试promise.all从内部开始尝试返回下载步骤resolve,然后return promise.all将下载的图像设置为LS。但这没有用。

贡特·佐克鲍尔

可能还有其他错误,但是缺少return

this.Tvlocalforage.setItem('meta', newMeta).then(() => { //Step 1
      for (let idx in ads) { //Step 2
        LSPromises.push(this.localforage.getItem(ads[idx]['filename']).then(blob => {
           if(!blob){ //Step 3
             return /* added return */ imgSrcToBlob(ads[idx]['S3URL'], undefined, 'Anonymous', 1).then((blob) => { //Step 4
              return this.localforage.setItem(ads[idx]['filename'], blob); //Step 5
            });
            // LSPromises.push(LSPromise);
           }
        }));
      }  
     // }).then(() => { 
      if(LSPromises.length) {
        return /* <<<=== */ Promise.all(LSPromises).then((data) => {
          this.TvLSkeyCount = LSPromises.length;
          this.fireLoadAssetsEvent(); //Step 6
        });
      } 
    });

如果未返回从中Promise.all()返回的承诺,则调用者将无法等待其完成。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章