Skip to content

Instantly share code, notes, and snippets.

@andrijac
Last active May 26, 2019 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrijac/61e36cea32519adbcd2c60d48ef234d5 to your computer and use it in GitHub Desktop.
Save andrijac/61e36cea32519adbcd2c60d48ef234d5 to your computer and use it in GitHub Desktop.
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function #20190526_1018
var timestamp = () => (new Date().getSeconds() + ' ' + new Date().getMilliseconds());
var resolveAfter2Seconds = function() {
console.log("starting slow promise " + timestamp());
return new Promise(resolve => {
setTimeout(function() {
resolve("slow " + timestamp());
console.log("slow promise is done " + timestamp());
}, 5000);
});
};
var resolveAfter1Second = function() {
console.log("starting fast promise " + timestamp());
return new Promise(resolve => {
setTimeout(function() {
resolve("fast " + timestamp());
console.log("fast promise is done " + timestamp());
}, 1000);
});
};
var sequentialStart = async function() {
console.log('==SEQUENTIAL START==');
// 1. Execution gets here almost instantly
const slow = await resolveAfter2Seconds();
console.log(slow); // 2. this runs 2 seconds after 1.
const fast = await resolveAfter1Second();
console.log(fast); // 3. this runs 3 seconds after 1.
}
var concurrentStart = async function() {
console.log('==CONCURRENT START with await==');
const slow = resolveAfter2Seconds(); // starts timer immediately
const fast = resolveAfter1Second(); // starts timer immediately
//Execution gets here almost instantly
console.log('Execution 1.');
console.log(await slow); // 2. this runs 2 seconds after 1.
console.log('Execution 2.');
console.log(await fast); // 3. this runs 2 seconds after 1., immediately after 2., since fast is already resolved
}
var concurrentPromise = function() {
console.log('==CONCURRENT START with Promise.all==');
return Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then((messages) => {
console.log(messages[0]); // slow
console.log(messages[1]); // fast
});
}
var parallel = async function() {
console.log('==PARALLEL with await Promise.all==');
// Start 2 "jobs" in parallel and wait for both of them to complete
await Promise.all([
(async()=>console.log(await resolveAfter2Seconds()))(),
(async()=>console.log(await resolveAfter1Second()))()
]);
}
// This function does not handle errors. See warning below!
var parallelPromise = function() {
console.log('==PARALLEL with Promise.then==');
resolveAfter2Seconds().then((message)=>console.log(message));
resolveAfter1Second().then((message)=>console.log(message));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment