Last active
May 4, 2019 14:39
-
-
Save rauschma/812fb1531e2e6946a3ab1705a7c6f59f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const assert = require('assert'); | |
//========== Helper functions | |
/** | |
* Resolves after `ms` milliseconds | |
*/ | |
function delay(ms) { | |
return new Promise((resolve, _reject) => { | |
setTimeout(resolve, ms); | |
}); | |
} | |
async function paused(id) { | |
console.log('START ' + id); | |
await delay(10); // pause | |
console.log('END ' + id); | |
return id; | |
} | |
//========== Main code | |
async function sequentialAwait() { | |
const result1 = await paused('first'); | |
assert.equal(result1, 'first'); | |
const result2 = await paused('second'); | |
assert.equal(result2, 'second'); | |
} | |
// Output: | |
// 'START first' | |
// 'END first' | |
// 'START second' | |
// 'END second' | |
async function concurrentPromiseAll() { | |
const result = await Promise.all([ | |
paused('first'), paused('second') | |
]); | |
assert.deepEqual(result, ['first', 'second']); | |
} | |
// Output: | |
// 'START first' | |
// 'START second' | |
// 'END first' | |
// 'END second' | |
async function concurrentAwait() { | |
const resultPromise1 = paused('first'); | |
const resultPromise2 = paused('second'); | |
assert.equal(await resultPromise1, 'first'); | |
assert.equal(await resultPromise2, 'second'); | |
} | |
// Output: | |
// 'START first' | |
// 'START second' | |
// 'END first' | |
// 'END second' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment