[英]Promise function with FileReader resolves prematurely
I'm opening a file to read contents like so: 我正在打开一个文件来读取内容,如下所示:
convertBlobToBase64(blob){
var convertPromise = new Promise(function(resolve, reject){
var fileReader = new FileReader();
fileReader.onload = function() {
var dataUrl = this.result;
var base64 = dataUrl.split(',')[1];
resolve(base64);
};
fileReader.readAsDataURL(blob);
});
return convertPromise;
}
I then call this function and pass the result data when it resolves: 然后,我调用此函数并在解析时传递结果数据:
myFunction(audioFile){
var to64 = this.convertBlobToBase64(audioFile);
to64.then(function(base64Val){
var nextPromise = postCall();
nextPromise.then(//stuff);
return nextPromise;
});
return to64;
}
However, when I call myFunction, it immediately returns a resolved promise that includes the converted data from convertBlobToBase64
, and not an unresolved promise that should be waiting on nextPromise
as expected. 但是,当我调用myFunction时,它立即返回一个已解析的
convertBlobToBase64
,其中包括来自convertBlobToBase64
的转换后的数据,而不是未解析的convertBlobToBase64
,该nextPromise
预期在nextPromise
上等待。
Instead, myFunction's .then is called immediately and fails as it doesn't have the correct data. 相反,myFunction的.then会立即调用,因为它没有正确的数据而失败。 Am I misunderstanding the Promise function?
我是否误解了Promise功能?
Try this code: 试试这个代码:
myFunction(audioFile){
var to64 = this.convertBlobToBase64(audioFile);
return to64.then(function(base64Val){
var nextPromise = postCall();
return nextPromise.then(//stuff);
});
}
Btw you dont need to wrap another promise to a function. 顺便说一句,您不需要将另一个Prom包装到函数。 You can use your postCall as resolve func and chain it like this:
您可以将postCall用作解析函数并将其链接起来,如下所示:
myFunction(audioFile){
return convertBlobToBase64(audioFile)
.then(base64Val => postCall())
.then(//stuff)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.