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()
¶
.catch()
catches errors in both the promise and infn1
vs
.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
- return in the
vs
- 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 asthrow 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);
}
- if you want to
throw
in an async callback (likesetTimeout
)
Return value in .catch()
¶
fetch
¶
Why do you need to await
fetch
calls twice?¶
response
returns when we get the first bit of datadata
returns when we get the rest of the data
Promises and TypeScript¶
Last update:
2023-04-24