Skip to content

Instantly share code, notes, and snippets.

@giovanniantonaccio
Last active September 20, 2019 17:49
Show Gist options
  • Save giovanniantonaccio/0f8f123da64ba5fde8249afd7ca43913 to your computer and use it in GitHub Desktop.
Save giovanniantonaccio/0f8f123da64ba5fde8249afd7ca43913 to your computer and use it in GitHub Desktop.
This gist simulates the execution of two async methods using async/await. It returns a message of success when both complete. A random timeout between 1 and 3000ms is being used.
function randomTimeout() {
const t = Math.floor(Math.random() * 3000 + 1);
return t;
}
// SetTimeout does not return a promise, so we can't await for it. This funcion promisify it mannualy.
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function method1() {
t = randomTimeout();
await timeout(t);
console.log("method1");
}
async function method2() {
t = randomTimeout();
await timeout(t);
console.log("method2");
}
Promise.all([method1(), method2()]).then(() => console.log("Success"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment