【发布时间】: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