Promise 的基本使用
為了解決回調地獄問題,從而給出的解決辦法:
/*** Promise** 1. Promise 是 一個構造函數 new Vue()* 2. Promise() 里面有個參數, 參數就是一個回調 () => {}* 回調也有參數* resolve f 操作成功的時候調用resolve => 調用 resolve => then()* reject f 操作失敗的時候調用reject* 3. 在 Promise里面放一個異步操作/*** 1. p 什么類型 Promise類型* 2. axios.get() Promise 類型* 3. axios.get().then()* 4. p.then()* xxxx.then() xxxx 大多數就是個promise*/const p = new Promise((resolve, reject) => {console.log('準備開始執行異步操作了')// 舉例 : 來一個異步操作setTimeout(() => {// 假如操作成功了 成功 == resolve == then// resolve('成功了')// 假如操作失敗了 失敗 == reject == catchreject('失敗了')}, 1000)
})p.then(res => {console.log('走then了', res)
}).catch(err => {console.log('走catch了', err)
})// axios.get().then()
讀取多個文件時可以使用:
ml_read('./a.txt').then(res => {console.log('a', res)return ml_read('./b.txt')}).then(res => {console.log('b', res)return ml_read('./c.txt')}).then(res => {console.log('c', res)})
async … await … 的使用
let fs = require('fs')
/*** @name ml_read* @desc 讀取多個文件* @param* @return*/
function ml_read(path) {//1. 創建 promise 實例let p = new Promise((resolve, reject) => {fs.readFile(path, 'utf-8', (err, data) => {if (err) {return reject('錯誤了')}resolve(data)})})//2. 返回 這個 promise 實例return p
}
// **************************** 上面是封裝好的 promise 函數 ml_read ***********/*** async 和 await 是 es8 提出來的* 作用 : 一種(編寫同步代碼的方式)處理異步的解決方案 , 處理的更加徹底** async 修飾一個(內部有await)函數 async function test() { }* await 修飾一個promise, 等待一個promise的結果 await promise類型*/async function test() {// then 其實就是等待一個結果(res)// ml_read('./a.txt').then(res => {// console.log(res)// })// await 其實也是等待一個結果(res)let resa = await ml_read('./a.txt')console.log(resa)let resb = await ml_read('./b.txt')console.log(resb)let resc = await ml_read('./c.txt')console.log(resc)
}test()/*** 使用了* 需求 : a => b => c*/
// ml_read('./a.txt')
// .then(res => {
// console.log('a', res)
// return ml_read('./b.txt')
// })
// .then(res => {
// console.log('b', res)
// return ml_read('./c.txt')
// })
// .then(res => {
// console.log('c', res)
// })
注意點及 try … catch … 的使用:
- 1.async 和 await 要成對出現
* 缺少async : SyntaxError: await is only valid in async function
* 缺少await : 打印的就是 promise 類型
* 2. 如何處理 async 和 await 的異常情況
* try…catch() 如果沒有問題 => 跳過 catch, 如果有問題就會被catch 捕獲
* 3. async 就近原則, async 添加到 await最近的函數前面 (小心回調)
三種狀態:
Promise的三種狀態
? * pending 待定
? * fulfilled 完成 <== resolve() 成功
? * rejected 拒絕 <== reject() 失敗
測試:對Ajax
進行Jquery
封裝
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><title>Document</title></head><body><script src="./node_modules/jquery/dist/jquery.js"></script><script>//http://localhost:3000// $.ajax({// // 類型// type: 'get',// // 接口// url: 'http://127.0.0.1:3000/post?pageIndex=1&pageSize=2&category=8',// // 參數// data: {},// // 數據返回類型// dataType: 'json',// // 成功// success: res => {// console.log('成功', res)// },// // 失敗// error: err => {// console.log('失敗', err)// },// })// 'http://127.0.0.1:3000/post?pageIndex=1&pageSize=2&category=8'// 自己手寫三遍function ml_ajax(options) {// 1. 創建 promise 實例let p = new Promise((resolve, reject) => {$.ajax({// 類型type: options.method || 'get',// 接口url: options.url,// 參數data: options.data || {},// 數據返回類型dataType: 'json',// 成功success: res => {// console.log('成功', res)resolve(res)},// 失敗error: err => {// console.log('失敗', err)reject(err)},})})// 2. 返回promise 實例return p}let url = 'http://127.0.0.1:3000/post?pageIndex=1&pageSize=2&category=8'ml_ajax({url,}).then(res => {console.log('666', res)})</script></body>
</html>