Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Call multiple functions with await
in parallel
If you try this code :
Sequential multiple awaits
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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();
Enter to Rename, Shift+Enter to Preview
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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();
Enter to Rename, Shift+Enter to Preview
You can await
anything
You can use the await
keyword even if the result is not a promise.
You can await anything
1
2
3
4
5
6
7
8
9
10
11
12
function job() {
return 'Hello world';
}
async function main() {
let message = await job();
console.log(message);
}
main();
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content