Search code examples
javascriptpromisepaintweb-performance

Use function from .then method of Promise outside its scope


I have a file called paintTiming.js, which uses the Paint Timing API for finding out Web Performance paramters such as First Paint and First Contextual Paint. The file contents are shown below:

var FP, FCP, obj = [];

function parent() {
    if ("PerformanceObserver" in window) {
        let observerPromise = new Promise((resolve, reject) => {
            // access the PerformanceObserver interface
            let observer = new PerformanceObserver((list) => {
                resolve(list);
            });

            observer.observe({
                entryTypes: ["paint"]
            });
        }).then((list) => {
            // Find out First Paint and First Contextual Paint
            FP = list.getEntries()[0].startTime;
            FCP = list.getEntries()[1].startTime;
            // Store in array
            obj[0] = FP;
            obj[1] = FCP;
            element = "The paint times are: <br> First Paint : " + FP + "ms, <br> First Contentful Paint : " + FCP + "ms";
            // show values on web page
            document.getElementsByTagName('p')[1].innerHTML = element;
        }).then(() => {
            // check if array is created, and is functioning
            console.log(obj[0]);
        }).then(() => {
            // create function
            function abc() {
                return {
                    a: obj[0],
                    b: obj[1]
                };
            };
        }).catch((error) => {
            console.warn(error);
        });
    }
};

As you can see, a function abc() should be created when the promise is resolved.

My question : How do I use this function outside the promise?

For example, consider the sample below (used in a HTML file):

<script type="text/javascript" src="paintTiming.js"></script>
<script type="text/javascript">
    // should return object containing FP and FCP values    
    console.log(abc());
</script>

The console shows that the function is not defined. If the JS code is inline, it still doesn't work.


Solution

  • You may not able to use the function if this is declared inside .then. Because this function abc is private to the callback function passed to .then & .then will only execute with the ajax.

    Alternatively you can define this function outside the Promise and call this function inside the .then callback. Also need to bind the context using this