簡體   English   中英

同步 base64 從 url 編碼

[英]Synchronous base64 encode from url

我是異步 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

您開始過度使用 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()));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM