Koa2

安装

npm i koa -S

开始

const Koa = require('koa')
const app = new Koa()

app.use(async(ctx) => {
  ctx.body = 'hello koa'
})

app.listen(3000)

什么是ctx

ctx就是封装了request和response的上下文

什么是next

下一个中间件

什么是app

启动应用

中间件

中间件是一种洋葱圈的模型,当你从中间件1next到了中间件2,最终你还将回到中间件1

image.png
const Koa = require('koa')
const app = new Koa()

app.use(async(ctx, next) => {
  ctx.body = '1'
  next()
  ctx.body += '2'
})
app.use(async (ctx, next) => {
  ctx.body += '3'
  next()
  ctx.body += '4'
})
app.use(async (ctx, next) => {
  ctx.body += '5'
  next()
  ctx.body += '6'
})

app.listen(3000)

结果为135642,next的作用就是执行下一个中间件

async await

解决callback hell

一个Promise的例子
const ajax = (word) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(word)
    }, 1000);
  })
}
ajax('you')
  .then(res => {
    console.log(res)
    return ajax('me')
  })
  .then(res => {
    console.log(res)
  })
async + await的例子

async + await一定要一起使用


async function start() {
  const word1 = await ajax('you')
  console.log(word1)
  const word2 = await ajax('me')
  console.log(word2)
  const word3 = await ajax('him')
  console.log(word3)
}
start()
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Koa 必须使用 7.6 以上的版本。如果你的版本低于这个要求,就要先升级 Node。 基本用法 Koa 提供一个...
    Gukson666阅读 2,490评论 0 1
  • Koa 学习 历史 Express Express是第一代最流行的web框架,它对Node.js的http进行了封...
    Junting阅读 2,852评论 0 0
  • 原文链接://www.greatytc.com/p/6b816c609669 前传 出于兴趣最近开始研究k...
    悬笔e绝阅读 7,248评论 1 11
  • 框架提出的背景 ES6/7带来的变革 自ES6确定和ES7中async/await开始普及,Node的发展变得更加...
    宫若石阅读 8,546评论 1 14
  • koa2 是由express原班人马打造的新一代web后端框架,相比express koa2更轻,代码也更优雅摆脱...
    贱贱贱贱贱阅读 17,520评论 1 8