ES6基础5(Promise)-学习笔记
生活随笔
收集整理的這篇文章主要介紹了
ES6基础5(Promise)-学习笔记
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- ES6基礎5(Promise)-學習筆記
- Promise
- 三個狀態
- 狀態轉換
- 手寫Promise源碼
- 同步異步概念
- jquery中
- 串行并行
- async-await
- 微任務 宏任務
ES6基礎5(Promise)-學習筆記
Promise
- 為什么需要?
- 依次加載3個請求 index.txt–>name.txt–>age.txt
- 使用fs代替http
- promise 解決無限嵌套
三個狀態
- pending 等待狀態
- fulfilled 成功狀態
- rejected 失敗狀態
狀態轉換
- 開始狀態pending,resolve()可轉變為成功狀態,reject變為失敗狀態
- 一旦狀態改變則不可改變
- resolve(xxx)數據會轉給then(成功,失敗)成功回調方法
- reject(yyy)數據會轉給then中失敗回調方法
- 是成功態就調成功回調 失敗態相同
- 需要把then中的成功、失敗回調保存
手寫Promise源碼
const SUCCESS = "fulfilled" const FAILURE = "rejected" const PENDING = "pending"function resolvePromise(value,resolve,reject){if(typeof value === 'function' || typeof value === 'object'){try{let then = value.then;if(typeof then === 'function'){then.call(value,x=>{//resolve(x)resolvePromise(x) //遞歸解析(如果參數也是Promise)},err=>{reject(err)})}else{resolve(value)}}catch(e){reject(e)}}else{resolve(value); //返回普通值} }class Promise{constructor(executor){this.status = PENDING; //初始狀態this.value = undefined; //保存成功態數據this.reason = undefined; //保存失敗態數據this.onFulfilledCallbacks = [];this.onRejectedCallbacks = [];let resolve = value => {if(this.status = PENDING){ //在等待態時才可修改this.status = SUCCESS; this.value = value;this.onFulfilledCallbacks.forEach(fn=>fn())}}let reject = reason => {if(this.status = PENDING){this.status = FAILURE; this.reason = reason;this.onRejectedCallbacks.forEach(fn=>fn())}}try{executor(resolve,reject);}catch(e){reject(e)}}then(onFulfilled,onRejected){ //成功回調 失敗回調let p = new Promise((resolve,reject)=>{//console.log(onFulfilled,onRejected)if(this.status = SUCCESS){ let v = onFulfilled(this.value)resolvePromise(v,resolve,reject)}if(this.status = FAILURE){ let v = onRejected(this.reason)resolvePromise(v,resolve,reject)}if(this.status = PENDING){this.onFulfilledCallbacks.push(() => {let v = onFulfilled(this.value)resolvePromise(v,resolve,reject)})this.onRejectedCallbacks.push(() => {let v = onRejected(this.reason)resolvePromise(v,resolve,reject)})}})return p;} }module.exports = Promise同步異步概念
//回調陷阱$.ajax({type:'get',url:'A',success:function(A){$.ajax({type:'get',url:'B/'+A,success:function(B){$.ajax({type:'get',url:'B/'+A,success:function(B){$.ajax({type:'get',url:'B/'+A,success:function(B){}})}})}})}});//promise 寫法var p = new Promise(function(resolve,reject){//resolve 成功后//reject 失敗后if(true){resolve("成功")}else {reject("失敗")}});p.then(function(resolved){//成功后},function(rejected){//失敗后});//解決回調問題//鏈式寫法var p = new Promise(function(resolve,reject){if(true){resolve("成功")}else {reject("失敗")}});p.then(function(resolved){console.log(resolved) // 成功//成功后return new Promise(function(resolve,reject){if(false){resolve("成功123")}else {reject("失敗123")}})},function(rejected){//失敗后}).then(function(resolved){//成功后console.log(resolved) // 成功123},function(rejected){//失敗后console.log(rejected) //"失敗123"});
原始http請求:
http請求封裝(promise):
//發送請求 url 接口地址 請求類型 type 傳的數據data const getJSON = function(url,type, data) {const promise = new Promise(function(resolve, reject){ const handler = function() {if (this.readyState !== 4) {return;};if (this.status === 200) {resolve(this.response); //成功后} else {reject(new Error(this.statusText)); //失敗了}};const client = new XMLHttpRequest();client.open(type, url);client.onreadystatechange = handler;client.responseType = "json";if(type =='get'){client.send();}else {client.setRequestHeader("Content-Type", "application/json");client.send(JSON.stringify(data));}});return promise;};調用請求:
//發送請求let getData = ()=>{getJSON('http://localhost:3333/get_table','get').then(res=>{//成功后console.log(res);},function(error){//失敗后});}jquery中
//jquery 高于1.5 defrred對象基于promise //then() done() // $.ajax({type:'get',url:this.url+"/get_table",dataType:'json' }).done(res=>{ //不支持延續任務的調用if(res.code=='200'){var data = JSON.parse(res.result);this.listShow(data);} }).fail(function(){});串行并行
串行:
并行:
async-await
//async的用法 作為一個關鍵字放在函數前面//具體的寫法async function f(){ //表示函數是一個異步函數return 'abc'};f(); //沒有執行abcconsole.log('xyz')//第二種方式async function f(){ //async函數返回一個promise,默認是成功狀態,并把函數的返回值傳給then的第一個參數return 'abc'};console.log(f()); //promiseconsole.log('xyz')//調用async function f(){ //async函數返回一個promise,默認是成功狀態,并把函數的返回值傳給then的第一個參數return 'abc'};f().then(res=>{console.log(res)});console.log('xyz');await-異步同步化
微任務 宏任務
//宏任務和微任務setTimeout(()=>{ //宏任務 console.log(1)},0)new Promise(function(resolve,reject){ //微任務resolve();console.log(2);}).then(function(){console.log(3)})//231setTimeout(()=>{ //宏任務 console.log(1)},0)new Promise(function(resolve,reject){ //微任務resolve();console.log(2);}).then(function(){console.log(3)});console.log(4)
總結
以上是生活随笔為你收集整理的ES6基础5(Promise)-学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ES6基础4(数据结构)-学习笔记
- 下一篇: TS基础1(类型定义、接口)-学习笔记