Skip to content

Instantly share code, notes, and snippets.

@datfinesoul
Last active February 3, 2021 04:16
Show Gist options
  • Save datfinesoul/e14b094063d91813613ca47d875882d8 to your computer and use it in GitHub Desktop.
Save datfinesoul/e14b094063d91813613ca47d875882d8 to your computer and use it in GitHub Desktop.
JS Examples: Failing to use await with async functions

A teaching example to show what happens when you don't have an await on an async method invocation.

Without the away, the program will print:

1612325635779 slowMessage start
1612325635781 leaving program
1612325637784 slowMessage end

When adding the await in front of slowMessage, the order is as expected:

1612325724509 slowMessage start
1612325726516 slowMessage end
1612325726516 leaving program
const timeout = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const slowMessage = async () => {
console.log(`${Date.now()} slowMessage start`);
await timeout(2000);
console.log(`${Date.now()} slowMessage end`);
}
(async () => {
// TODO: The next line needs an await, but see what happens without it
slowMessage();
console.log(`${Date.now()} leaving program`);
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment