同步从 DataTransferItem 中提取值 - 我在这里做什么(错误)?
我有一个用于 drop
事件的处理函数,它看起来像这样:
da.addEventListener("drop", function(e) {
e.stopPropagation();
var xhr = new XMLHttpRequest();
... (configure XMLHttpRequest)
var fd = new FormData();
[...e.dataTransfer.items].forEach(it => {
it.getAsString(value => {
console.log(`append ${it.type} ${value}`);
fd.append(`${it.type}`, value);
});
});
console.log("send");
xhr.send(fd);
});
这里的问题是 send()
在 fd.append()
之前发生>,因为 it.getAsString()
似乎是异步的。
在阅读了一些有关回调、异步函数、promise 等的文章后,我尝试在 .then()
块中进行实际的附加操作:
it.getAsString(value => {
return value;
}).then(value => {
console.log(`append ${it.type} ${value}`);
fd.append(`${it.type}`, value);
});
我预计会遇到 value
的麻烦没有被正确传播,但我得到了
Uncaught TypeError: it.getAsString(...) is undefined
,甚至集成调试器也强调了getAsString
。
我在这里做什么?为什么当我在不附加 .then(value => {})
的情况下使用它时,似乎定义了 getAsString
,但在没有 .then()
的情况下却可以正常工作>?
在更抽象的层面上 - 在发送之前如何正确地将 items
从 DataTransferItem
添加到 FormData
实例?
更新
结合迭代 .items
然后使用 .getData()
对我有用,但感觉不对。
[...e.dataTransfer.items].forEach(it => {
fd.append(`${it.type}`, e.dataTransfer.getData(it.type));
});
I have a handler function for the drop
event which looks somehow like this:
da.addEventListener("drop", function(e) {
e.stopPropagation();
var xhr = new XMLHttpRequest();
... (configure XMLHttpRequest)
var fd = new FormData();
[...e.dataTransfer.items].forEach(it => {
it.getAsString(value => {
console.log(`append ${it.type} ${value}`);
fd.append(`${it.type}`, value);
});
});
console.log("send");
xhr.send(fd);
});
The problem here is that send()
happens before fd.append()
, because it.getAsString()
seems to be asynchronous.
After reading some articles about callbacks, asynchronous functions, promises etc. I tried to do the actual appending in a .then()
block:
it.getAsString(value => {
return value;
}).then(value => {
console.log(`append ${it.type} ${value}`);
fd.append(`${it.type}`, value);
});
I expected to get into trouble with value
not being propagated properly but instead I got
Uncaught TypeError: it.getAsString(...) is undefined
And even the integrated debugger underlines getAsString
.
What am I doing here? Why seems getAsString
to be defined when I use it without appending .then(value => {})
but works properly without .then()
?
On a more abstract level - how would I correctly add items
from a DataTransferItem
to a FormData
instance before sending it?
Update
Combining iterating through .items
and then using .getData()
works for me but it doesn't feel right..
[...e.dataTransfer.items].forEach(it => {
fd.append(`${it.type}`, e.dataTransfer.getData(it.type));
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论