等待Base64映像在javascript异步循环中返回值



我正在做一场让异步循环工作的噩梦。我需要检索一个图像作为数据来做一些事情,但我能返回的只是"未定义",它不需要等待结果!!简单地说,我需要检索数据图像并将其传递给下一个函数,但无法等待!!

代码在这里

function getImages(aID){
async function getFileContentAsBase64(path, callback){
window.resolveLocalFileSystemURL(path, gotFile, fail);
function fail(e) {
alert('Cannot found requested file');
}
function gotFile(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var content = this.result;
console.log('content looks as it should:::', content);
callback(content);
};
reader.readAsDataURL(file);
});
}
}
console.log("aData uploadImages:", aData);
console.log("aData.length:", aData.length);
(async () => {
console.log("in sync length:::" + aData.length);
for (let i = 0; i < aData.length; i++) {
console.log("in loop:::")
//  toastSuccess("fetching image.--.")
var fileURL = 'filepath/filename.jpg';
console.log(i + "-LOOKING FOR:::", fileURL);
const getImage = await getFileContentAsBase64(fileURL, function(base64Image {//<<<<HERE HERE HERE --THIS IS THE ISSUE
console.log("base64Image LOOKS AS IT SHOULD:::", base64Image);
});
console.log(i + "-IMAGEDATA COMES back as undefined", getImage);//<<<HERE HERE HERE - this is the issue. I need to get this value before the loop continues!!!
console.log(i + "-s::: GOT IMAGE");
//    toastSuccess("sending image. .-")
var oParams = {id:1}//,body:getImage
var sendImage = await doSomethingElse(getImage, oParams);
}
})();
}

明白了。它需要一个promise,还从页面顶部的function getFileContentAsBase64(. .中删除了异步。

const getImageAsData = (file) => new Promise((resolve, reject) => {
getBase64(file, (base64Image) => {
resolve(base64Image);
reject('error on return');
})
});

感谢

最新更新