Search code examples
javascriptasynchronousasync-awaites6-promise

JavaScript ES7 - Call async function at top of page, await at bottom


I'm comfortable with regular async/await functions, but I'm looking for something a little more complex.

I want to make an async AJAX call at the top of the page, while that's fetching, continue loading the rest of the page, but at the bottom, or after page load, start another JS function that awaits for the initial call made earlier to complete & use the data.

The motivation is pretty simple, right? Start off the async AJAX call, in the meantime load the rest of the page, then use the data when all the HTML, CSS, Images, etc, has loaded. Or am I overlooking something simple & obvious?

I'm willing to fall back on Promises if necessary, but still not clear to me how to do it.

Thanks for any thoughts...

Chris


Solution

  • Top of the page:

    const pendingResult = fetch(someUrl);
    

    End of the page:

    pendingResult.then(result=>console.log("result is:",result));
    

    Or if you want to use async/await:

    async function doSomethingWithResult(){
      const result = await pendingResult;
      //....
    }
    doSomethingWithResult();