1

how can i define a function, that is called asynchronously?

async function getPosts() {
    for (i = 0; i < 1000000000; i++){}
    console.log("loop done.");
}

console.log("start");
getPosts();
console.log("end");

the result is:
start
loop done.
end


i was expecting:
start
end
loop done

i expect that, because the function "getPosts" is declared as "async". so the we dont wait until the function is finished.

How do i have to adjust my code to get the expected result?

Dev1
  • 11
  • 1

3 Answers3

2

The async function could be the one calling another function that returns a Promise. Inside the Promise you could put a setTimeout instead of the for loop and finall make the call with asyncCall:

function getPosts() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('done.');
    }, 2000);
  });
}


async function asyncCall() {
  var result = await getPosts();
  console.log(result);
}

console.log("start");
asyncCall();
console.log("end");
shrys
  • 5,860
  • 2
  • 21
  • 36
1

The main reason why your code don't do the "async" thing, it's because of the way js threads works. A FOR loop will use the main thread to do the job soooo, the code will wait it finish de loop. The @shys answer works, but without the loop. If you want a working async, take a look at the WebWorker api

Mauricio Sipmann
  • 465
  • 6
  • 21
  • Thank you. But how is the fetch()-Method implemented? The fetch-Method doesn't use the main-thread? Because i have to wait for the result. – Dev1 Jul 18 '19 at 13:21
  • ok, talking about [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) it's a different thing. Fetch is kind of a browser code, so it will run outside the main thread till it finish. Look at [this post](https://stackoverflow.com/questions/50046841/proper-way-to-make-api-fetch-post-with-async-await) – Mauricio Sipmann Jul 18 '19 at 13:26
  • See [this example](https://jsfiddle.net/rxk16o7n/) of how call a function, run some code and at the end, waits for the request if it's not already returned. – Mauricio Sipmann Jul 18 '19 at 13:32
0

To sum up what Mauricio Sipmann and shrys correctly told: An asynchronous function is a function which operates asynchronously via the event loop (see async function). In order to continue executing the calling context of your async function getPosts(), i. e. with console.log("end"), the event loop must be given a chance to pause the execution of getPosts(), e. g. with this variant of your function:

function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)) }

async function getPosts() {
    for (i = 0; i < 1000; i++) { await sleep(3) } // pause for 3 ms
    console.log("loop done.");
}

console.log("start");
getPosts();
console.log("end");

But how is the fetch()-Method implemented?

fetch() likely contains such an await statement, so that the event loop can continue executing while fetch() is waiting for the HTTP response.

Community
  • 1
  • 1
Armali
  • 18,255
  • 14
  • 57
  • 171