async await practice

This commit is contained in:
aminamos
2020-04-07 08:45:15 -07:00
parent 50dd179b22
commit 93b3c2ac48

View File

@@ -1,18 +1,56 @@
import setText , {appendText} from './results.mjs';
export function get(){
export async function get(){
const {data} = await axios.get("http://localhost:3000/orders/1")
setText(JSON.stringify(data))
}
export function getCatch(){
export async function getCatch(){
try {
const {data} = await axios.get("http://localhost:3000/orders/123")
setText(JSON.stringify(data))
} catch (error) {
setText(error)
}
}
export function chain(){
export async function chain(){
const {data} = await axios.get("http://localhost:3000/orders/1")
const {data: address} = await axios.get(`http://localhost:3000/addresses/${data.shippingAddress}`)
setText(`City: ${JSON.stringify(address.city)}`)
}
export function concurrent(){
// even if orders finishes first,
// data won't show until orderStatus finishes
// then it'll move to orders
export async function concurrent(){
const orderStatus = axios.get("http://localhost:3000/orderStatuses")
const orders = axios.get("http://localhost:3000/orders")
setText("")
const {data: statuses} = await orderStatus
const {data: allOrders} = await orders
appendText(JSON.stringify(statuses))
appendText(JSON.stringify(allOrders[0]))
}
export function parallel(){
// run at same time
export async function parallel(){
setText("")
await Promise.all([
(async () => {
const {data} = await axios.get("http://localhost:3000/orderStatuses")
appendText(JSON.stringify(data))
})(),
(async () => {
const {data} = await axios.get("http://localhost:3000/orders")
appendText(JSON.stringify(data))
})()
])
}