Back
Close

JavaScript, async and await keywords

Magus
8,871 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');
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');
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);
}
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