Executing Code in Parallel — JavaScript

Let’s learn how to fire off JavaScript code in parallel. Speeding up execution time!

Serverless Guru
Oct 28, 2018 · 4 min read

Let’s Jump In.

const responses = await Promise.all([promise1, promise2, promise3])for(let response of responses) {  // do something
}

Scenario:

Bad:

let response1 = await executeQuery("SELECT * FROM table where id = 1")let response2 = await executeQuery("SELECT * FROM table where id = 1")...// format responses// respond to client

Good:

let promise1 = new Promise((resolve) => resolve(executeQuery(...))let responses = await Promise.all([promise1, promise2, promise3, ...])for(let response of responses) {
// format responses

// respond to client
}

Test Code:

function makeRequest() {
return new Promise((resolve) => {
setTimeout(() => resolve({ 'status': 'done' }), 2000);
});
}
async function process(arrayOfPromises) {
console.time(`process`);
let responses = await Promise.all(arrayOfPromises);
for(let r of responses) {}
console.timeEnd(`process`); return;
}
async function handler() {
let arrayOfPromises = [
makeRequest(),
makeRequest(),
makeRequest(),
makeRequest(),
makeRequest(),
];

await process(arrayOfPromises);
console.log(`processing is complete`);
}
handler();

Results:

Test #1:

process: 2002.60400390625msprocessing is complete

Test #2:

process: 2005.722900390625msprocessing is complete

Test #3:

process: 2001.069091796875msprocessing is complete

Conclusion:

Additional Content:

What does Serverless Guru do?

What did we miss?

https://www.serverlessguru.com

Ryan Jones

Serverless Guru

Serverless Guru is a cloud consulting and training company specializing in Serverless development and cloud optimization.

Serverless Guru

Written by

Exploring the unknown and helping elevate the entire community through written word. https://www.serverlessguru.com

Serverless Guru

Serverless Guru is a cloud consulting and training company specializing in Serverless development and cloud optimization.