Async & Await / Promises

Async

Main function

1
(async () => {
2
throw new Error('Hello World');
3
})().catch((err) => console.error(err));
Copied!

With Promises

1
async () => {
2
await new Promise(...);
3
const [
4
result1,
5
result2,
6
] = await Promise.all([
7
new Promise(),
8
new Promise(...)],
9
);
10
return value;
11
}
Copied!

Promises

When you start chaining a lot of promises and passing variables around, consider usings aysnc instead.
Pay attention to the style, because it's really stupid.
1
const start = new Promise((resolve, reject) => {
2
xhr.get(url)
3
.success((result) => resolve(result))
4
.failure((error) => reject(error));
5
});
6
7
const afterStart = (startResult) => new Promise((resolve, reject) => {
8
});
9
10
start
11
.then(afterStart)
12
// Always start on a new line, its easier to catch
13
// Always use a Promise or only { Promise.all([]) }, its eaiser to catch
14
.then() => new Promise((resolve, reject) => {
15
})
16
.catch((error) => {
17
console.log(error);
18
});
Copied!
    Always have a catch() to ensure you can see all errors.

Promise.all

Gotcha:
    You have to call .catch() on each of the promises
    You should only catch things which are idempotent; for example:
      Sending emails
1
await Promise.all([
2
...,
3
...,
4
].map((promise) => promise.catch(error => console.error(error))));
Copied!
Last modified 2yr ago