【问题标题】:waiting for Base64 image to return value in javascript async loop等待Base64图像在javascript异步循环中返回值
【发布时间】:2020-05-04 11:34:38
【问题描述】:

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

这是代码

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);

      }
  })();
}

【问题讨论】:

    标签: javascript loops asynchronous async-await


    【解决方案1】:

    知道了:它需要一个承诺,还从页面顶部的“function getFileContentAsBase64(. .”中删除了异步

    const getImage = new Promise((resolve, reject) => { getFileContentAsBase64(sfileURL, function(base64Image){ resolve(base64Image); reject('返回错误');}) });

    谢谢.--。 . .- -.-。 .

    【讨论】:

      猜你喜欢
      • 2020-03-13
      • 1970-01-01
      • 1970-01-01
      • 2018-09-25
      • 2011-03-04
      • 2021-06-01
      • 2012-05-04
      • 2014-11-26
      • 1970-01-01
      相关资源
      最近更新 更多