Javascript 如何从getBoundingClientRect中的Promise结果对象获取特定值?
下面是我返回承诺的部分代码,我使用getBoundingClientRect Async,因为它在AMP虚拟DOM(AMP脚本)中运行: JS: 控制台日志:Javascript 如何从getBoundingClientRect中的Promise结果对象获取特定值?,javascript,asynchronous,virtual-dom,getboundingclientrect,ampscript,Javascript,Asynchronous,Virtual Dom,Getboundingclientrect,Ampscript,下面是我返回承诺的部分代码,我使用getBoundingClientRect Async,因为它在AMP虚拟DOM(AMP脚本)中运行: JS: 控制台日志: Promise {<pending>} __proto__: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: Object bottom: 366 height: 38 left: 225 right: 352.234375 top: 328
Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
bottom: 366
height: 38
left: 225
right: 352.234375
top: 328
width: 127.234375
x: 328
y: 225
__proto__: Object
Promise{}
__承诺
[[PromiseState]]:“已履行”
[[PromiserResult]]:对象
底图:366
身高:38
左:225
右:352.234375
顶部:328
宽度:127.234375
x:328
y:225
__原型:对象
如何从对象承诺结果中获取left
的值?
coords.left
返回未定义的如果getBoundingClientRectAsync
返回承诺,则可以使用获取值
button.addEventListener("mouseenter", async function(event){
let target = event.target;
let coords = await target.getBoundingClientRectAsync();
console.log(coords.left);
});
或者使用返回的Promise的方法,设置一个回调,当Promise解析时,coords
对象在该回调中可用
button.addEventListener("mouseenter", function(event){
let target = event.target;
target.getBoundingClientRectAsync().then(coords => {
console.log(coords.left);
});
});
了解有关承诺的基本知识。第二种解决方案有效!等待解决方案会抛出一个错误,告知出于某种原因它不是异步函数。我将查看链接,非常感谢。
button.addEventListener("mouseenter", function(event){
let target = event.target;
target.getBoundingClientRectAsync().then(coords => {
console.log(coords.left);
});
});