Javascript Run Asynchronous Simultaneously Sep 11th 2019 Words: 253
This post is created a year ago, the content may be outdated.

Life is a lot easier with Async/Await, you can write clean code to handle async operations, for example:

1
2
3
4
5
6
7
8
async (arg) => {
try {
let result = await doFirstJob(arg);
return await doSecondJob(result);
} catch (e) {
throw new Error('Oops!');
}
}

But if the an asynchronous function contains operations that are independent, for example:

1
2
3
4
5
6
7
8
async () => {
try {
await watchYoutube();
await haveMeal();
} catch (e) {
console.log(e.message);
}
}

The problem is that the haveMeal is always executed after the watchYoutube, even though they have no dependency relationship and can be executed at the same time.

Removing await keyword is not an option because it will cause the inability to catch any error thrown by those two function call, and unhandled promise rejection is not what should occur.

There are some not-so-clean workaround, for example, wrap the async operations in functions that handled the exception seperately:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
let asyncWatchYoutube = () => {
try {
await watchYoutube();
} catch (e) {
console.log(e.message);
}
}

let asyncHaveMeal = () => {
try {
await haveMeal();
} catch (e) {
console.log(e.message);
}
}

async () => {
try {
asyncWatchYoutube();
asyncHaveMeal();
} catch (e) {
console.log(e.message);
}
}

Another workaround, according to this SO post:

1
2
3
4
5
6
7
8
async () => {
try {
let [firstResult, secondResult] = await Promise.all([watchYoutube(), haveMeal()]);
//Promise will be rejected if any of the watchYoutube(), haveMeal() is rejected
} catch (e) {
console.log(e.message);
}
}

EOF