Javascript 使用承诺将HTML5 FileReader的结果捕获到变量
我有一个Angular 4应用程序,其中我正在读取一个图像&试图将base64字符串传递给另一个变量-但是由于其异步性质,我遇到了一个问题-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
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{}?承诺把我弄糊涂了:)为什么在使用承诺时要使用回调?