从URL同步base64编码

时间:2019-09-19 10:52:03

标签: javascript asynchronous xmlhttprequest base64 synchronous

我是异步javascript的新手,并且熟悉异步/等待方式。 但是我面临一个问题。

我正在尝试使用xhr获取图像并将其转换为base64,并将结果传递给回调。

但是我的回调中的控制台日志出现在应该位于末尾的控制台日志之后。

我尝试了很多事情,但不知道自己在做什么错。我只希望代码的执行是同步的。

一些帮助将不胜感激。

这是我的代码:

    function toDataUrl(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onload = async function() {
    var reader = new FileReader();
    reader.onloadend = async function() {
      await callback(reader.result);
    };
    reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
}

for (const element of data.elements) { // This is inside an async function
            let index_elem = tabMission.findIndex(x => x.id == element.id);
            if (index_elem === -1) {
              let codes = [];
              $.each(element.codes, (code, position) => {
                codes.push({ code: code, position: position, isSaved: false });
              });
              window.localStorage.setItem('photos', JSON.stringify([]));
              for (const photo of element.photos) {
                await toDataUrl(
                  base_url + 'storage/images/elements/' + photo,
                  async result => {
                    let photos = JSON.parse(
                      window.localStorage.getItem('photos')
                    );
                    photos.push(result);
                    console.log(JSON.stringify(photos));
                    window.localStorage.setItem(
                      'photos',
                      JSON.stringify(photos)
                    );
                  }
                );
              }
              //setTimeout(() => {
              console.log(JSON.parse(window.localStorage.getItem('photos'))); // This prints at the end of logs
              tabMission.push({
                id: element.id,
                title: element.title,
                codes: codes,
                photos: JSON.parse(window.localStorage.getItem('photos')),
                toSynchronize: false
              });
              setTabMissionById(tabMission, request['mission_id']);
              // }, 5000);
            }
          }
          console.log(getTabMissionById($('#mission_id').val())); // This should print after all logs

1 个答案:

答案 0 :(得分:3)

您过度使用async / await作为开始,toDataUrl甚至没有返回Promise来等待-这是您的顺序下降的地方

function toDataUrl(url) {
    return new Promise((resolve, reject) => {
        var xhr = new XMLHttpRequest();
        xhr.onload = function () {
            var reader = new FileReader();
            reader.onloadend = function () {
                resolve(reader.result);
            };
            reader.readAsDataURL(xhr.response);
        };
        xhr.onerror = reject;
        xhr.open('GET', url);
        xhr.responseType = 'blob';
        xhr.send();
    });
}

for (const element of data.elements) { // This is inside an async function
    let index_elem = tabMission.findIndex(x => x.id == element.id);
    if (index_elem === -1) {
        let codes = [];
        $.each(element.codes, (code, position) => {
            codes.push({
                code: code,
                position: position,
                isSaved: false
            });
        });
        window.localStorage.setItem('photos', JSON.stringify([]));
        for (const photo of element.photos) {
            const result = await toDataUrl(base_url + 'storage/images/elements/' + photo);
            let photos = JSON.parse(window.localStorage.getItem('photos'));
            photos.push(result);
            console.log(JSON.stringify(photos));
            window.localStorage.setItem('photos',JSON.stringify(photos));
        }
        console.log(JSON.parse(window.localStorage.getItem('photos'))); // This prints at the end of logs
        tabMission.push({
            id: element.id,
            title: element.title,
            codes: codes,
            photos: JSON.parse(window.localStorage.getItem('photos')),
            toSynchronize: false
        });
        setTabMissionById(tabMission, request['mission_id']);
        // }, 5000);
    }
}
console.log(getTabMissionById($('#mission_id').val()));
相关问题