Skip to content

Non-intro Promise Notes

Intro to promises

Promise error handling

Promise.finally doesn't affect the return value of the function

result = getJson()
    .then((data) => "data")
    .catch((error) => "error")
    .finally(() => "do something");
  • “result” will either be “data” or “error” if an error is caught

Order of .then() vs .catch()

p.then(fn1).catch(fn2);
  • .catch() catches errors in both the promise and in fn1

vs

p.catch(fn2).then(fn1);
  • .catch() only catches errors in the promise
  • useful if you want to continue the promise chain and run fn1
    • return in the catch
    • re-throw an error to keep the Promise rejected

vs

p.then(fn1, fn2);
  • ensures that only one function ever gets called

[Promise.reject() vs throw] (https://stackoverflow.com/questions/33445415/javascript-promises-reject-vs-throw)

  • Promise.reject(new Error()) is the same as throw new Error()
async function test() {
    result = await promise1
        .catch((error) => {
            return Promise.reject("Hi"); // will trigger the second catch
        })
        .catch((error) => {
            //
            console.log(`Second catch: ${error}`);
            return error;
        });
    console.log(result);
}

Return value in .catch()

Promise.reject(e);

fetch

Why do you need to await fetch calls twice?

const response = await fetch("url");
const data = response.json();
  1. response returns when we get the first bit of data
  2. data returns when we get the rest of the data

Promises and TypeScript


Last update: 2023-04-24