Back
Close

JavaScript, async and await keywords

Magus
6,225 views

Call multiple functions with await in parallel

If you try this code :

Sequential multiple awaits
const start = Date.now();
function timeLog(text) {
console.log(`${Date.now() - start}ms - ${text}`);
}
function job() {
return new Promise(function(resolve, reject) {
timeLog('Job start');
setTimeout(function() {
timeLog('Job done');
resolve('Hello world');
}, 500);
});
}
async function main() {
let message1 = await job(),
message2 = await job(),
message3 = await job();
timeLog(message1);
timeLog(message2);
timeLog(message3);
}
main();
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

You can see that the job function is called sequentially. But in such code, you probably want to make the 3 calls in parallel. You have to use your old friend Promise.all

Parallel multiple awaits
const start = Date.now();
function timeLog(text) {
console.log(`${Date.now() - start}ms - ${text}`);
}
function job() {
return new Promise(function(resolve, reject) {
timeLog('Job start');
setTimeout(function() {
timeLog('Job done');
resolve('Hello world');
}, 500);
});
}
async function main() {
let messages = await Promise.all([job(), job(), job()]);
messages.forEach(function(message) {
timeLog(message);
});
}
main();
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

You can await anything

You can use the await keyword even if the result is not a promise.

You can await anything
function job() {
return 'Hello world';
}
async function main() {
let message = await job();
console.log(message);
}
main();
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants