koa2-Koa-generator腳手架

Koa-generato腳手架

安裝

npm install -g koa-generator

創建koa2項目

// koa2 project    默認使用jade模板引擎
koa2 –e koa2-learn  // -e表示使用ejs引擎 koa2-learn爲項目名 

在這裏插入圖片描述

安裝依賴

npm install

如果出現下面的提示
在這裏插入圖片描述

npm install --update-binary

啓動服務

// 代碼有修改 需要手動重新啓動
npm strat  
//  上下二選一
// 代碼有修改 自動重新啓動
npm run dev

訪問

localhost:3000
// package.json
  "scripts": {
    "start": "node bin/www",
    "dev": "./node_modules/.bin/nodemon bin/www",
    "prd": "pm2 start bin/www",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

npm start
npm test
其他的得加run
npm run dev
npm run prd

node中全局對象爲global;web頁面全局對象爲window

router.get('/testAsync', async (ctx) => {
  global.console.log('start', new Date().getTime())
  const a = await new Promise((resolve, reject) => {
    setTimeout(() => {
      global.console.log('async a', new Date().getTime())
      resolve('hello world')
    }, 1000)
  })
  const b = await 'node'
  const c = await new Promise((resolve, reject) => {
    setTimeout(() => {
      global.console.log('async a', new Date().getTime())
      resolve('javascript')
    }, 2000)
  })
  // await運行完 纔會執行下面的代碼
  ctx.body = {
    a,
    b,
    c
  }
})

訪問http://localhost:3000/testAsync時
在這裏插入圖片描述
在這裏插入圖片描述

await相當於用同步的寫法,完成的異步的過程
await得到返回後,纔會繼續執行下面的代碼
await後面跟一個promise對象.如果不是,會自動轉化爲promise對象

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章