gpt4 book ai didi

Javascript - 从 FileReader 异步 onload 方法获取值

转载 作者:行者123 更新时间:2023-11-28 04:13:19 30 4
gpt4 key购买 nike

我知道这个问题已经被问过很多次了,但我已经查看了这些答案,但无法使我的代码工作。我正在使用 Angular 2。我有用于文件插入的输入标签。文件到达组件,但是当我将其转换为数组缓冲区并尝试将其设置为变量时,我的变量仍然未定义。我尝试实现回调,但我认为我做错了。

这是我的代码:

addPlayer() {
var nationality = document.getElementById("nationality") as HTMLSelectElement;
var position = document.getElementById("position") as HTMLSelectElement;
var shirtnmbr = document.getElementById("shirtnmbr") as HTMLSelectElement;
var profilePicture = document.getElementById("profilepic") as HTMLSelectElement;
var inGamePicture = document.getElementById("detailspic") as HTMLSelectElement;
var player = {
Club_ID: this.clubId,
Name: this.capitalization(this.addForm.get("name").value),
Surname: this.capitalization(this.addForm.get("surname").value),
Height: this.addForm.get("height").value,
Weight: this.addForm.get("weight").value,
BirthDate: this.addForm.get("birthdate").value.formatted,
Nationality: this.nationalities[nationality.selectedIndex],
Position: this.order[position.selectedIndex],
Shirtnmbr: this.shirtNumbers[shirtnmbr.selectedIndex],
ProfilePicture: this.conversion(profilePicture, function (res) {
return res;
}),
InGamePicture: this.conversion(inGamePicture, function (res) {
return res;
})
};
console.log(player);
}

capitalization(str) {
return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
}

conversion(element, callback) {
var file = element.files;
var result;
var fileReader = new FileReader();
fileReader.onload = function () {
result = fileReader.result;
callback(result);
};
fileReader.readAsArrayBuffer(file[0]);
}

当我登录玩家时,除了 ProfilePicture 和 InGamePicture(它们未定义)之外,每个属性都有值。之后,我计划将该玩家发送到数据库,但目前我无法这样做,因为 http.post 将在 ProfilePicture 和 InGamePicture 属性获取值之前运行。

最佳答案

您将 ProfilePictureInGamePicture 设置为等于 conversion() 的返回值的值,该值永远不会返回任何内容,因此它们始终会未定义。您提供了一个调用的回调,但它实际上什么也没做(返回从未处理过的参数)。

您需要同步完成两个 FileReader 操作才能继续。如果您只能异步获取结果,那么这听起来像是 Promises 的工作,目前处理多个异步操作控制流的首选方法。

关于Javascript - 从 FileReader 异步 onload 方法获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46075032/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com