Javascript 从url同步base64编码

Javascript 从url同步base64编码,javascript,asynchronous,xmlhttprequest,base64,synchronous,Javascript,Asynchronous,Xmlhttprequest,Base64,Synchronous,我不熟悉异步javascript,并且熟悉异步/等待方式。 但我面临一个问题 我正在尝试使用xhr获取一个图像,并将其转换为base64,将结果传递给回调 但是回调中的控制台日志出现在控制台日志之后,控制台日志应该在末尾出现 我尝试了很多事情,但不知道我做错了什么。我只希望代码的执行是同步的 非常感谢您的帮助 这是我的密码: function toDataUrl(url, callback) { var xhr = new XMLHttpRequest(); xhr.onload

我不熟悉异步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
甚至没有返回一个等待的承诺-这就是您的序列失败的原因

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

首先,您过度使用了async/await,而且
toDataUrl
甚至没有返回一个等待的承诺-这就是您的序列失败的原因

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

等待数据URL
。。。问题是,
toDataUrl
不会将
Promise
返回给
await
——您可以使用
fetch
,它已经是基于Promise的,因此可以等待它。。。或者您可以在
toDataUrl
why is
async result=>{
async?函数中没有任何异步功能,也没有使用仅用于测试目的的
await
@JaromandaX hahahathanks for your response tho:)它帮助我理解了这个问题!
await todata url
…问题是
todata url
没有向
await
返回
承诺您可以改为使用
fetch
,这已经是基于承诺的,因此可以等待…或者您可以在
toDataUrl
中“提示”代码
async result=>{
async?函数中没有任何异步功能,也没有使用
wait
@JaromandaX,它只是用于测试目的。hahaThanks为您的答案,tho:)它帮助我理解了这个问题!