我可以打印从promise收到的值但不能打印其array.length

时间:2017-07-12 09:44:21

标签: javascript angular typescript

response screenshot image 我从JavaScript承诺中收到一系列值。当我console.log时,我可以打印它的价值。但无法打印其array.length。请参阅getImageUrl()方法中的注释

    public saveImages() {        
        for (let img of this.multipleImages) {
            if (img.file) {
                this.promise = this.FileUploadService.
                    addFile(img.file, img.randomName);
                this.promise.then(result => { 
                    this.setImageUrl(result);
                });
            }                     
        }
    }
    setImageUrl(result) {
        this.imageUrl.push(result);
    }
    getImageUrl() {
        console.log(this.imageUrl.length, // length is always 0
            this.imageUrl[0], //undefined
            this.imageUrl); // has  value (result from promise)
    }
    ngOninit() {
        this.saveImages();//saves the image and calls the setImageUrl method.
        this.getImageUrl();
    }

当调用this.getImageUrl()时,你可以在getImageUrl()方法的console.log中看到什么是print和什么不是。

1 个答案:

答案 0 :(得分:0)

尝试删除for循环&在该循环中每次迭代都跳过覆盖this.promise实例。

所以,像这样:

const saveImages = () => Promise.all(this.multipleImages
  .map(img => img && img.file ? this
    .FileUploadService.addFile(img.file, img.randomName)
    .then(this.setImageUrl.bind(this)) : null
  ))

 // Then use with:
 saveImages()
   .then(() => this.getImageUrl())

顺便说一句,我在这里处理这些承诺的想法:https://github.com/justsml/escape-from-callback-mountain/