0%

12. Async, Koa

Async Patterns

  1. Callbacks

too complicated -> simplified in ES6

  1. Promises
    reduce too many handlings, make into clean code (sugar coding)

Promise -> invoke reject/ resolve as callbacks

then -> happen arg first and then ‘then’ method

  • resolve : when we find the answer
  • reject : st went wrong
  1. Async / Await
  • async === setTimeOut
  • await : pending promise/ valid answer from crypto.compare

☝️

callback functions are stacked
: first cb -> first wait + call the second stacked callback function
second cb -> second wait + third callback

✌️

nested callback functions
wait for set time and execute the next one

=> create new Promise and put setTimeOut in it, use resolve function

async
=> create asyn function, use await

print 1 time

  • async itself is just a normal function, but return the value as Promise

Koa

Search everything by ‘koa ~’

  • promise based -> always use ‘async’ !
  • app.use() : go to the next() middleware
  • express : req/res each send/receive info to/from the client
    koa : ctx controls everything, koa sends/receives the info all by itself, control everything related to the client

await next() -> call bodyParser -> call router -> call allowedMethods…
*** install packages needed !!

  • controller -> usually the end of the chain (next -> next -> … -> ctrl)
  • controller doesn’t send anything to the client (no res.send()) => app (koa obj) sends the info to the client after receiving everything from the chain of next & controller

response aliases : Not method!, just variables!

  • ctx.request.body -> approach the request of body

Pre-requisite

code . // vscode
npm init –y // npm initialise
touch index.js router.js controller.js // make files
npm i koa
@ npm i “koa pkg” // search!

index.js

middleware ( 1 -> 2 -> 3 ) -> router: doorman –> controller: manager)

  • app.use(router) : always the last, right before to the controller

set the middleware next(), which is the ‘router.routes()’ in this case

router.js

const Router = require(‘koa-router’)

controller.js

get the id as params.id

  • all the vars sent via the address are saved in the ctx.request.params!
    e.g. /:name/:id –> ctx.request.params.name, ctx.request.params.id