mirror of
https://github.com/jackyzha0/quartz.git
synced 2025-12-24 21:34:06 -06:00
vault backup: 2022-07-29 11:10:53
This commit is contained in:
parent
8800ef8ad9
commit
9d2e01160c
@ -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}')
|
||||
})
|
||||
```
|
||||
|
||||
Loading…
Reference in New Issue
Block a user