aws s3 bucket 图片在 angular6 中上传有问题 return

aws s3 bucket image upload in angular6 having problem in return

我正在使用这种方法将图像上传到 aws s3 存储桶: https://grokonez.com/aws/angular-4-amazon-s3-example-how-to-upload-file-to-s3-bucket

这作为一项单独的任务工作得很好,但就我而言,由于异步行为可能会晚一点出现结果。我希望在确认后立即执行下一个任务。

upload() {
      let file: any;
      // let urltype = '';
      let filename = '';
      // let b: boolean;
      for (let i = 0 ; i < this.urls.length  ; i++) {
        file = this.selectedFiles[i];
        // urltype = this.urltype[i];
        filename = file.name;
        const k = uuid() + '.' + filename.substr((filename.lastIndexOf('.') + 1));
        this.uploadservice.uploadfile(file, k);
        console.log('done');
        // console.log('file: ' + file + ' : ' + filename);
        // let x = this.userservice.PostImage('test', file);
         // console.log('value of ' + x);
      }
      // return b;
     }

文件上传服务:

bucket.upload(params, function (err, data) {
      if (err) {
        console.log('There was an error uploading your file: ', err);
        return false;
      }
      console.log('Successfully uploaded file.', data);
      return true;
    }).promise();
  }

这里,done 是在文件上传完成之前执行。

我认为您应该查看异步编程教程并尝试使用简单的超时来尝试几个示例来掌握它,然后继续进行更复杂的事情,例如 s3 和 aws。

以下是我建议您开始旅程的方式:

1) 使用纯JS学习异步编程的基本概念 https://eloquentjavascript.net/11_async.html

2) 使用回调和超时试验您自己的示例

3) 用 Promises 替换回调

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

4) 使用 rxjs Observables(类似于 JS Observable)"angular" 方式

http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html

PS:更具体地说:

您的代码失败,因为以下行是以异步方式执行的。因此,代码将调用您的 uploadfile 函数并将立即继续执行而无需等待。

this.uploadservice.uploadfile(file, k);

一旦你遵循了我上面描述的所有要点,你将能够做这样的事情(使用 Promise):

this.uploadservice.uploadfile(file, k)
  .then( result => {
     console.log('Upload finished');
   })
  .catch(error => {
     console.log('Something went wrong');
  });