From 9d2e01160c7ce0d100e90b6de5f30ad5a98781f3 Mon Sep 17 00:00:00 2001 From: Jet Hughes Date: Fri, 29 Jul 2022 11:10:53 +1200 Subject: [PATCH] vault backup: 2022-07-29 11:10:53 --- content/notes/06-async-javascript.md | 43 ++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/content/notes/06-async-javascript.md b/content/notes/06-async-javascript.md index c5d3c0cb3..178e2e3c6 100644 --- a/content/notes/06-async-javascript.md +++ b/content/notes/06-async-javascript.md @@ -8,19 +8,19 @@ tags: Async programming allows you to start a potentially long running task have still be able to interact while it it running -general process +# general process - start the task - return immediately so other tasks can run - notify us with result when the task is finished -promises +# promises - an object returned by an async function - represents the current state of the operation - when the promise is returned to the caller it not always finished - the promise object has methods to handle the eventual success or failure of the operation -``` +``` javascript const fetchPromise = fetch('https://url.url.json') fetchPromise @@ -31,3 +31,40 @@ fetchPromise console.log(data[0].name) }) ``` + +each `.then` itself returns another promise which also has a `.then` method. This is called **promise chaining** + + +## promise statuses + +**pending:** the promise is created but the task has not finished yet +**fulfilled:** the task has finished successfully -> `then()` is called +**rejected:** the task has failed -> `catch()` is called +**settled:** fulfilled or rejected + +## combining promises + +```javascript +Promise.all([fetchPromsise1, fetchPromsise2, fetchPromsise3]) //all promises need to be fulfilled but they dont depend of each other +Promise.any([fetchPromsise1, fetchPromsise2, fetchPromsise3]) //any +``` + +# error handling +the fetch API can throw errors + +to handle these promise objects have a `catch` method. this is similar to a `.then` but only trigger when there is an error. + +``` javascript +const fetchPromise = fetch('https://url.url.json') + +fetchPromise + .then((reponse) => { + return response.json(); + }) + .then((data) => { + console.log(data[0].name) + }) + .catch((error) => { + console.error('could not get products: ${error}') + }) +```