如何从 getBoundingClientRect 中的 Promise 结果对象获取特定值?

问题描述

这是我返回 Promise 的代码的一部分,我使用 getBoundingClientRect Async 因为它在 AMP 虚拟 DOM (amp-script) 中运行:

JS:

    button.addEventListener("mouseenter",function(event){
    
       let target = event.target;

       let coords = target.getBoundingClientRectAsync();
       
       console.log(coords);

    });

控制台日志:

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 Result 中获取 left 的值? coords.left; 返回未定义

解决方法

如果 getBoundingClientRectAsync 返回一个 promise,那么您可以使用 async / await 来获取值。

button.addEventListener("mouseenter",async function(event){
  let target = event.target;
  let coords = await target.getBoundingClientRectAsync();
  console.log(coords.left);
});

或者使用返回的 Promise 的 then 方法并设置一个回调,当 Promise 解析时,您的 coords 对象可用。

button.addEventListener("mouseenter",function(event){
  let target = event.target;
  target.getBoundingClientRectAsync().then(coords => {
    console.log(coords.left);
  });
});

了解 Promise 的基础知识 here on MDN