Created
June 8, 2017 08:38
-
-
Save nidin/e2e6d59184c10adcca9833e4f050bb73 to your computer and use it in GitHub Desktop.
JavaScript Async Await Sequential and Parallel Test
This file contains hidden or 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
async function testSequential() { | |
async function f1 (){ | |
let promise = new Promise((resolve, reject) => { | |
setTimeout(()=>{resolve(2)}, 2000); | |
}); | |
return promise; | |
} | |
async function f2 (){ | |
let promise = new Promise((resolve, reject) => { | |
setTimeout(()=>{resolve(2)}, 2000); | |
}); | |
return promise; | |
} | |
console.time("first await finished"); | |
let r1 = await f1(); | |
console.timeEnd("first await finished"); | |
console.time("second await finished"); | |
let r2 = await f2(); | |
console.timeEnd("second await finished"); | |
return r1 + r2; | |
} | |
async function testParallel() { | |
async function f1 (){ | |
let promise = new Promise((resolve, reject) => { | |
setTimeout(()=>{resolve(2)}, 2000); | |
}); | |
return promise; | |
} | |
async function f2 (){ | |
let promise = new Promise((resolve, reject) => { | |
setTimeout(()=>{resolve(2)}, 2000); | |
}); | |
return promise; | |
} | |
console.time("await finished"); | |
let r1 = await Promise.all([f1(),f2()]); | |
console.timeEnd("await finished"); | |
return r1[0] + r1[1]; | |
} | |
async function start(){ | |
console.time("testParallel"); | |
let result = await testParallel(); | |
console.log(result); | |
console.timeEnd("testParallel"); | |
console.time("testSequential"); | |
result = await testSequential(); | |
console.log(result); | |
console.timeEnd("testSequential"); | |
} | |
start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment