【问题标题】:Synchronous base64 encode from url从 url 同步 base64 编码
【发布时间】:2019-09-19 19:07:36
【问题描述】:

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

我正在尝试使用 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

【问题讨论】:

  • await toDataUrl ... 问题是toDataUrl 不会将Promise 返回到await - 您可以改用fetch,因为它已经基于Promise,所以它可以等待......或者你可以“承诺”toDataUrl中的代码
  • 为什么async result => { 是异步的?函数中没有异步,也没有使用await
  • @JaromandaX 仅用于测试目的哈哈
  • 感谢您的回答 :) 它帮助我理解了这个问题!

标签: javascript asynchronous xmlhttprequest base64 synchronous


【解决方案1】:

你开始过度使用 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()));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-03
    • 2020-07-20
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多