浅谈promise用es5实现
生活随笔
收集整理的這篇文章主要介紹了
浅谈promise用es5实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
作為新人第一次擼博客,寫的不好 多多包涵
?由于JavaScript所有的代碼都是單線程執行的 所以es6的時候出現了promise
?promise作為es6的異步操作構造函數有all、reject、resolve這幾個方法,其原型上then、catch等方法;其有三種狀態分別為
pending進行中,resolve已完成,reject失敗
1.接下來我們進入正題,這篇博客內容主要是為了更加深刻的理解promise的原理:
//那new一個把 var test = new Promise(function(resolve, reject){resolve('數據'); });? promise作為一個構造函數,接收的參數是個函數,傳入兩個參數(resolve,reject)分別表示異步操作執行成功和失敗的回調;
? resolve把狀態從pending變成resolve,reject把狀態從pending變成reject
? 一般我們用promise的時候是包在一個函數中,在需要的時候去調用運行它:
function Async(){var test = new Promise(function(resolve,reject){resolve("成功返回數據")})return test; }Async()
?接下來我們就可以調用它:
Async().then(function(res){console.log(res)//....
//可以對傳過來的數據進行一系列操作 })
你還可以不斷地then進行回調進行鏈式操作用法:
promise成功解決了之前es5的回調地獄
用代碼來展示下promise的精髓:
function Async1(){var p = new Promise(function(resolve, reject){resolve('隨便什么數據1');});return p; } function Async2(){var p = new Promise(function(resolve, reject){resolve('隨便什么數據2');});return p; } function Async3(){var p = new Promise(function(resolve, reject){resolve('隨便什么數據3');});return p; }Async1() .then(function(data){console.log(data);return Async2(); }) .then(function(data){console.log(data);return Async3(); }) .then(function(data){console.log(data); });//接下來可以清楚的看到:
// 隨便什么數據1
// 隨便什么數據2
// 隨便什么數據3
?
2.promise的用法已經介紹了,接下來我們來用es5實現promise:
function promise (fn) {if (typeof this !== 'object') { throw new TypeError('Promises must be constructed via new');}if (typeof fn !== 'function') {throw new TypeError('Promise constructor\'s argument is not a function');}this.state = "pending"; //定義狀態this.msg="";var process=arguments[0];var that=this;process(function(){that.state="resolve"that.msg=arguments[0]},function(){that.state="reject"that.msg=arguments[0]})return this}promise.prototype.then=function(){constructor:promiseif(this.state == "resolve"){arguments[0](this.msg)}else if(this.status=='reject'&&arguments[1]){arguments[1](this.msg)}promise=new this.constructor(function (resolve,reject) {resolve("2")}) //每次調用then之后重新返回一個新的promise實例進行下一步then的調用// console.log(this)// console.log(promise)return promise}var mm = new promise(function(resolve,reject){resolve("1")})mm.then(function(res){ //then回調 console.log(res)}).then(function(res){console.log(res)})?
轉載于:https://www.cnblogs.com/xweizi/p/10089876.html
總結
以上是生活随笔為你收集整理的浅谈promise用es5实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 12/7个人站立会议
- 下一篇: c. Litmxs找女友