Bill
Bill

Reputation: 2973

run await functions one after one

There are a lot of samples on running Async/Await functions. But only with one await call.

I don't find a right sample that I can run await functions one after one

async function a() {
   console.log('this is function a');
   // do something
}
async function b() {
   console.log('this is function b');
   // do something
}
async function c() {
   console.log('this is function c');
   // do something
}

async function main() {

  await a();

  await b();

  await c();

}

main();

Test with above code (hide the real code), I found it is not guaranteed, function c will be executed last.

How can I adjust it?

Node version:

$ node --version
v10.15.3

Upvotes: 0

Views: 94

Answers (1)

JasperZelf
JasperZelf

Reputation: 2844

Like the comments on your question say: your example code will always run in the right order.

In the comments you mention that if there are hundreds of lines of code, it does not always run that way.

Could it be that somewhere in that code you use things like setTimeout()?

Since setTimeout runs in a separate execution context, the async/await will not wait for it to finish. I have updated your example to demonstrate this.

async function a() {
  console.log('this is function a - 1');
	await getResponse();
  console.log('this is function a - 2');
}

async function b() {
   console.log('this is function b - 1');
   setTimeout(()=>{
   	console.log('this is function b - 2')
   }, 500);
}
async function c() {
   console.log('this is function c');
}

async function main() {
  await a();
  await b();
  await c();
}

function getResponse() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
    	console.log('setTimeout finished');
      resolve("Response from API. Executed after 5 secs");
    }, 500);
  });
}


main();

Upvotes: 1

Related Questions