Links

Async & Await / Promises

Async

Main function

(async () => {
throw new Error('Hello World');
})().catch((err) => console.error(err));

With Promises

async () => {
await new Promise(...);
const [
result1,
result2,
] = await Promise.all([
new Promise(),
new Promise(...)],
);
return value;
}

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.
const start = new Promise((resolve, reject) => {
xhr.get(url)
.success((result) => resolve(result))
.failure((error) => reject(error));
});
const afterStart = (startResult) => new Promise((resolve, reject) => {
});
start
.then(afterStart)
// Always start on a new line, its easier to catch
// Always use a Promise or only { Promise.all([]) }, its eaiser to catch
.then() => new Promise((resolve, reject) => {
})
.catch((error) => {
console.log(error);
});
  • 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
await Promise.all([
...,
...,
].map((promise) => promise.catch(error => console.error(error))));
Last modified 4yr ago