Search code examples
javascriptasynchronousvirtual-domgetboundingclientrectampscript

How to get specific value from Promise Result Object in getBoundingClientRect?


Here is part of my code returning a Promise, I am using getBoundingClientRect Async because it runs in AMP virtual DOM (amp-script):

JS:

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

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

    });

Console Log:

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

How I can get value of left from the object Promise Result? coords.left; returns undefined


Solution

  • If getBoundingClientRectAsync returns a promise, then you can use async / await to get the value.

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

    Or use the then method of the returned Promise and set a callback where your coords object is made available when the Promise resolves.

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

    Learn the basics about Promises here on MDN.