目錄
ES6 模塊化
1、什么是 ES6 模塊化規(guī)范
2、在 node.js 中體驗 ES6 模塊化
3、ES6 模塊化的基本語法
Promise
1. 回調(diào)地獄
2、Promise 的基本概念
3、基于回調(diào)函數(shù)按順序讀取文件內(nèi)容
4.、基于 then-fs 讀取文件內(nèi)容
4.1 then-fs 的基本使用
4.2 .then() 方法的特性
4.3 基于 Promise 按順序讀取文件的內(nèi)容
4.4 通過 .catch 捕獲錯誤
4.5 Promise.all() 方法
4.6 Promise.race() 方法
5. 基于 Promise 封裝讀文件的方法
1 getFile 方法的基本定義
2 創(chuàng)建具體的異步操作
3 獲取 .then 的兩個實參
4 調(diào)用 resolve 和 reject 回調(diào)函數(shù)
async/await
1. 什么是 async/await
2. async/await 的基本使用
3. async/await 的使用注意事項
EventLoop
1. JavaScript 是單線程的語言
2. 同步任務(wù)和異步任務(wù)
3. 同步任務(wù)和異步任務(wù)的執(zhí)行過程
4. EventLoop 的基本概念
5. 結(jié)合 EventLoop 分析輸出的順序
宏任務(wù)和微任務(wù)
1. 什么是宏任務(wù)和微任務(wù)
2. 宏任務(wù)和微任務(wù)的執(zhí)行順序
API 接口案例
1. 案例需求
2. 主要的實現(xiàn)步驟
3. 搭建項目的基本結(jié)構(gòu)
4. 創(chuàng)建基本的服務(wù)器
5. 創(chuàng)建 db 數(shù)據(jù)庫操作模塊
6. 創(chuàng)建 user_ctrl 模塊
7. 創(chuàng)建 user_router 模塊
8. 導(dǎo)入并掛載路由模塊
9. 使用 try…catch 捕獲異常
ES6 模塊化
1、什么是 ES6 模塊化規(guī)范
- ?每個 js 文件都是一個獨立的模塊
- ?導(dǎo)入其它模塊成員使用 import 關(guān)鍵字
- ?向外共享模塊成員使用 export 關(guān)鍵字
2、在 node.js 中體驗 ES6 模塊化
3、ES6 模塊化的基本語法
- ?默認導(dǎo)出與默認導(dǎo)入
- ?按需導(dǎo)出與按需導(dǎo)入
- ?直接導(dǎo)入并執(zhí)行模塊中的代碼
Promise
1. 回調(diào)地獄
2、Promise 的基本概念
- ?我們可以創(chuàng)建 Promise 的實例 const p = new Promise()
- ?new 出來的 Promise 實例對象,代表一個異步操作
- ?每一次 new Promise() 構(gòu)造函數(shù)得到的實例對象,
- ?都可以通過原型鏈的方式訪問到 .then() 方法,例如 p.then()
- ?p.then(成功的回調(diào)函數(shù),失敗的回調(diào)函數(shù))
- ?p.then(result => { }, error => { })
- ?調(diào)用 .then() 方法時,成功的回調(diào)函數(shù)是必選的、失敗的回調(diào)函數(shù)是可選的
3、基于回調(diào)函數(shù)按順序讀取文件內(nèi)容
4.、基于 then-fs 讀取文件內(nèi)容
npm i then-fs
4.1 then-fs 的基本使用
//通過默認導(dǎo)入
import thenFs from 'then-fs'
4.2 .then() 方法的特性
4.3 基于 Promise 按順序讀取文件的內(nèi)容
import thenFs from 'then-fs'
thenFs
.readFile('./files/1.txt', 'utf8')
.then((r1) => {
console.log(r1)
return thenFs.readFile('./files/2.txt', 'utf8')
})
.then((r2) => {
console.log(r2)
return thenFs.readFile('./files/3.txt', 'utf8')
})
.then((r3) => {
console.log(r3)
})
4.4 通過 .catch 捕獲錯誤
.catch((err) => {
console.log(err.message)
})
4.5 Promise.all() 方法
import thenFs from 'then-fs'
const promiseArr = [
thenFs.readFile('./files/3.txt', 'utf8'),
thenFs.readFile('./files/2.txt', 'utf8'),
thenFs.readFile('./files/1.txt', 'utf8'),
]
Promise.all(promiseArr).then(result => {
console.log(result)
})
4.6 Promise.race() 方法
Promise.race(promiseArr).then(result => {
console.log(result)
})
5. 基于 Promise 封裝讀文件的方法
1 getFile 方法的基本定義
function getFile(fpath) {
return new Promise
}
2 創(chuàng)建具體的異步操作
function getFile(fpath) {
return new Promise(function () {
fs.readFile(fpath, 'utf8', (err, dataStr) => {
})
})
}
3 獲取 .then 的兩個實參
通過 .then() 指定的成功和失敗的回調(diào)函數(shù),可以在 function 的形參中進行接收,
4 調(diào)用 resolve 和 reject 回調(diào)函數(shù)
Promise 異步操作的結(jié)果,可以調(diào)用 resolve 或 reject 回調(diào)函數(shù)進行處理。
import fs from 'fs'
function getFile(fpath) {
return new Promise(function (resolve, reject) {
fs.readFile(fpath, 'utf8', (err, dataStr) => {
if (err) return reject(err)
resolve(dataStr)
})
})
}
getFile('./files/11.txt')
.then((r1) => {
console.log(r1)
})
.catch((err) => console.log(err.message))
async/await
1. 什么是 async/await
2. async/await 的基本使用
import thenFs from 'then-fs'
async function getAllFile() {
const r1 = await thenFs.readFile('./files/1.txt', 'utf8')
console.log(r1)
}
getAllFile()
3. async/await 的使用注意事項
- 如果在 function 中使用了 await,則 function 必須被 async 修飾
-
在 async 方法中,第一個 await 之前的代碼會同步執(zhí)行,await 之后的代碼會異步執(zhí)行
console.log('A') async function getAllFile() { console.log('B') const r1 = await thenFs.readFile('./files/1.txt', 'utf8') console.log(r1) const r2 = await thenFs.readFile('./files/2.txt', 'utf8') console.log(r2) const r3 = await thenFs.readFile('./files/3.txt', 'utf8') console.log(r3) console.log('D') } getAllFile() console.log('C') //輸出 結(jié)果 A B 111、、 D
EventLoop
1. JavaScript 是單線程的語言
JavaScript 是一門單線程執(zhí)行的編程語言。也就是說,同一時間只能做一件事情。
2. 同步任務(wù)和異步任務(wù)
- ?又叫做非耗時任務(wù),指的是在主線程上排隊執(zhí)行的那些任務(wù)
- ?只有前一個任務(wù)執(zhí)行完畢,才能執(zhí)行后一個任務(wù)
- ?又叫做耗時任務(wù),異步任務(wù)由 JavaScript 委托給宿主環(huán)境進行執(zhí)行
- ?當(dāng)異步任務(wù)執(zhí)行完成后,會通知 JavaScript 主線程執(zhí)行異步任務(wù)的回調(diào)函數(shù)
3. 同步任務(wù)和異步任務(wù)的執(zhí)行過程
- ?同步任務(wù)由 JavaScript 主線程次序執(zhí)行
- 異步任務(wù)委托給宿主環(huán)境執(zhí)行
- ?已完成的異步任務(wù)對應(yīng)的回調(diào)函數(shù),會被 加入到任務(wù)隊列中等待執(zhí)行
- ?JavaScript 主線程的執(zhí)行棧被清空后,會 讀取任務(wù)隊列中的回調(diào)函數(shù),次序執(zhí)行
- ?JavaScript 主線程不斷重復(fù)上面的第 4 步
4. EventLoop 的基本概念
5. 結(jié)合 EventLoop 分析輸出的順序
同步任務(wù)。會根據(jù)代碼的先后順序依次被執(zhí)行
宏任務(wù)和微任務(wù)
1. 什么是宏任務(wù)和微任務(wù)
- ?異步 Ajax 請求、
- ?setTimeout、setInterval、
- ?文件操作
- ?其它宏任務(wù)
- ?Promise.then、.catch 和 .finally
- ?process.nextTick
- ?其它微任務(wù)
2. 宏任務(wù)和微任務(wù)的執(zhí)行順序
API 接口案例
1. 案例需求
- ?第三方包 express 和 mysql2
- ?ES6 模塊化
- ?Promise
- ?async/await
2. 主要的實現(xiàn)步驟
- ?搭建項目的基本結(jié)構(gòu)
- ?創(chuàng)建基本的服務(wù)器
- ?創(chuàng)建 db 數(shù)據(jù)庫操作模塊
- ?創(chuàng)建 user_ctrl 業(yè)務(wù)模塊
- ?創(chuàng)建 user_router 路由模塊
3. 搭建項目的基本結(jié)構(gòu)
創(chuàng)建一個文件目錄 用vscode打開?
初始包 npm? init -y?
- ?在 package.json 中聲明 "type": "module"
- ?運行 npm install express@4.17.1 mysql2@2.2.5
4. 創(chuàng)建基本的服務(wù)器
新建app.js
import express from 'express'
const app = express()
app.listen(80, () =>{
console.log('serve run 127.0.0.1')
})
運行 nodemon app.js?
5. 創(chuàng)建 db 數(shù)據(jù)庫操作模塊
新建 db/index.js
數(shù)據(jù)庫中必須有數(shù)據(jù)
import mysql from 'mysql2'
const pool = mysql.createPool({
host: '127.0.0.1',
port: '3306',
database: 'test',
user: 'root',
password: '123456',
})
export default pool.promise()
6. 創(chuàng)建 user_ctrl 模塊
新建?user_ctrl.js? ? ?運行 :node?user_ctrl.js?
import db from '../db/index.js'
export async function getAllUser(req, res){
const [rows] = await db.query('select id, username, password from user' )
console.log(rows)
res.send({
status: 0,
message: '獲取用戶成功',
data: rows,
})
}
7. 創(chuàng)建 user_router 模塊
新建route /user_router.js?文章來源:http://www.zghlxwxcb.cn/news/detail-604020.html
import express from 'express'
import { getAllUser } from '../controller/user_ctrl.js'
const router = new express.Router()
router.get('/user', getAllUser)
export default router
8. 導(dǎo)入并掛載路由模塊
import express from 'express'
import userRouter from './router/user_router.js'
const app = express()
app.use('/api', userRouter)
app.listen(80, () =>{
console.log('serve run 127.0.0.1')
})
9. 使用 try…catch 捕獲異常
import db from '../db/index.js'
export async function getAllUser(req, res){
try {
const [rows] = await db.query('select id, username, password from user' )
console.log(rows)
res.send({
status: 0,
message: '獲取用戶成功',
data: rows,
})
}catch(err){
res.send({
status: 1,
message: '獲取用戶失敗',
desc: err.message,
})
}
}
運行 :nodemon app.js文章來源地址http://www.zghlxwxcb.cn/news/detail-604020.html
到了這里,關(guān)于ES6模塊化與異步編程高級用法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!