0

I need to do multiple ajax fetches to populate a web page, and would like to render the different parts of the page as the results arrive. Is it possible to do this using async / await syntax, or do I have to do the older-style callbacks with promises?

This question is similar, but does not have the answer: Call async/await functions in parallel The accepted answer in this question is to use Promise.all(...), which doesn't return any results until all of the results resolve.

I know I can do this with:

myPromise.then(function(value) {
  // populate part of page here
});

myOtherPromise.then(function(value) {
  // populate other part of page here
});

but I'm trying to use the newer await syntax.

ccleve
  • 15,239
  • 27
  • 91
  • 157

2 Answers2

3

You could use something like:

(async () => {
    const value = await myPromise;
    // then do your stuff with value
})();

(async () => {
    const value = await myOtherPromise;
    // then do your stuff with value
})();
Jean-Baptiste Martin
  • 1,399
  • 1
  • 10
  • 19
-1

To my knowledge, it's not possible to do this because async/await is used to add synchronous patterns to asynchronous code. However, there are some other ways around this, one example being:

(async () => {
  const res = await fetch("https://example.com");
  document.querySelector("#example").innerHTML = await res.text();
})();

(async () => {
  alert("Is the internet on? " + ( await fetch("http://example.com/")).ok )
})();

Pawel Uchida-Psztyc
  • 3,735
  • 2
  • 20
  • 41