Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/456.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用承诺将HTML5 FileReader的结果捕获到变量_Javascript_Asynchronous_Promise_Base64_Filereader - Fatal编程技术网

Javascript 使用承诺将HTML5 FileReader的结果捕获到变量

Javascript 使用承诺将HTML5 FileReader的结果捕获到变量,javascript,asynchronous,promise,base64,filereader,Javascript,Asynchronous,Promise,Base64,Filereader,我有一个Angular 4应用程序,其中我正在读取一个图像&试图将base64字符串传递给另一个变量-但是由于其异步性质,我遇到了一个问题-image.src为空,因此该值已正确传递给图像对象 ngAfterViewInit(): void { let image = new Image(); var promise = this.getBase64(fileObject, this.processImage()); promise.then(function(base6

我有一个Angular 4应用程序,其中我正在读取一个图像&试图将base64字符串传递给另一个变量-但是由于其异步性质,我遇到了一个问题-
image.src
为空,因此该值已正确传递给图像对象

ngAfterViewInit(): void {
    let image = new Image();
    var promise = this.getBase64(fileObject, this.processImage());
    promise.then(function(base64) {
        console.log(base64);    // outputs string e.g 'data:image/jpeg;base64,........'
    });

    image.src = base64; // how to get base64 string into image.src var here??          
}

/**
 * get base64 string from supplied file object
 */
public getBase64(file, onLoadCallback) {
    return new Promise(function(resolve, reject) {
        var reader = new FileReader();
        reader.onload = function() { resolve(reader.result); };
        reader.onerror = reject;
        reader.readAsDataURL(file);
    });
}

public processImage() {

}

您遇到的问题是
base64
是变量,作用域在
的回调函数中。then()
。要使其正确,只需执行以下操作:

ngAfterViewInit(): void {
    let image = new Image();
    var promise = this.getBase64(fileObject, this.processImage());
    promise.then(function(base64) {    // base64 variable is scoped to this function only.
        console.log(base64);    // outputs string e.g 'data:image/jpeg;base64,........'

        image.src = base64;
    });
}

您遇到的问题是
base64
是变量,作用域在
的回调函数中。then()
。要使其正确,只需执行以下操作:

ngAfterViewInit(): void {
    let image = new Image();
    var promise = this.getBase64(fileObject, this.processImage());
    promise.then(function(base64) {    // base64 variable is scoped to this function only.
        console.log(base64);    // outputs string e.g 'data:image/jpeg;base64,........'

        image.src = base64;
    });
}

是否需要向processImage()添加任何内容?目前,我在代码中的
image.src=base64
行上获得了一个不可分配给字符串的'type{}?承诺把我弄糊涂了:)使用承诺时为什么要使用回调?我需要向processImage()添加什么吗?目前,我在代码中的
image.src=base64
行上获得了一个不可分配给字符串的'type{}?承诺把我弄糊涂了:)为什么在使用承诺时要使用回调?