Skip to content

Instantly share code, notes, and snippets.

@Lucasdsk
Created January 19, 2022 01:30
Show Gist options
  • Save Lucasdsk/045cffa39aaf75196405296388e8dfea to your computer and use it in GitHub Desktop.
Save Lucasdsk/045cffa39aaf75196405296388e8dfea to your computer and use it in GitHub Desktop.
Testing a delayed setTimeout using Promise
const timeoutWithAwait = async () =>
await setTimeout(() => {
console.log("[timeoutWithAwait] - timed out");
}, 500);
const timeoutWithPromise = () =>
new Promise((resolve) =>
setTimeout(() => {
console.log("[timeoutWithPromise] - timed out");
resolve();
}, 500)
);
const testTimeoutWithAwait = async () => {
console.log("[timeoutWithAwait] - start");
await timeoutWithAwait();
console.log("[timeoutWithAwait] - done");
};
const testTimeoutWithPromise = async () => {
console.log("[timeoutWithPromise] - start");
await timeoutWithPromise();
console.log("[timeoutWithPromise] - done");
};
// Test 1
testTimeoutWithAwait();
// Output:
// [timeoutWithAwait] - start
// [timeoutWithAwait] - done
// [timeoutWithAwait] - timed out
// Test 2
testTimeoutWithPromise();
// Output:
// [timeoutWithPromise] - start
// [timeoutWithPromise] - timed out
// [timeoutWithPromise] - done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment