浅谈promise用es5实现
作為新人第一次擼博客,寫的不好 多多包涵
?由于JavaScript所有的代碼都是單線程執(zhí)行的 所以es6的時(shí)候出現(xiàn)了promise
?promise作為es6的異步操作構(gòu)造函數(shù)有all、reject、resolve這幾個(gè)方法,其原型上then、catch等方法;其有三種狀態(tài)分別為
pending進(jìn)行中,resolve已完成,reject失敗
1.接下來(lái)我們進(jìn)入正題,這篇博客內(nèi)容主要是為了更加深刻的理解promise的原理:
//那new一個(gè)把 var test = new Promise(function(resolve, reject){resolve('數(shù)據(jù)'); });? promise作為一個(gè)構(gòu)造函數(shù),接收的參數(shù)是個(gè)函數(shù),傳入兩個(gè)參數(shù)(resolve,reject)分別表示異步操作執(zhí)行成功和失敗的回調(diào);
? resolve把狀態(tài)從pending變成resolve,reject把狀態(tài)從pending變成reject
? 一般我們用promise的時(shí)候是包在一個(gè)函數(shù)中,在需要的時(shí)候去調(diào)用運(yùn)行它:
function Async(){var test = new Promise(function(resolve,reject){resolve("成功返回?cái)?shù)據(jù)")})return test; }Async()
?接下來(lái)我們就可以調(diào)用它:
Async().then(function(res){console.log(res)//....
//可以對(duì)傳過(guò)來(lái)的數(shù)據(jù)進(jìn)行一系列操作 })
你還可以不斷地then進(jìn)行回調(diào)進(jìn)行鏈?zhǔn)讲僮饔梅?#xff1a;
promise成功解決了之前es5的回調(diào)地獄
用代碼來(lái)展示下promise的精髓:
function Async1(){var p = new Promise(function(resolve, reject){resolve('隨便什么數(shù)據(jù)1');});return p; } function Async2(){var p = new Promise(function(resolve, reject){resolve('隨便什么數(shù)據(jù)2');});return p; } function Async3(){var p = new Promise(function(resolve, reject){resolve('隨便什么數(shù)據(jù)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); });//接下來(lái)可以清楚的看到:
// 隨便什么數(shù)據(jù)1
// 隨便什么數(shù)據(jù)2
// 隨便什么數(shù)據(jù)3
?
2.promise的用法已經(jīng)介紹了,接下來(lái)我們來(lái)用es5實(shí)現(xiàn)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"; //定義狀態(tài)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")}) //每次調(diào)用then之后重新返回一個(gè)新的promise實(shí)例進(jìn)行下一步then的調(diào)用// console.log(this)// console.log(promise)return promise}var mm = new promise(function(resolve,reject){resolve("1")})mm.then(function(res){ //then回調(diào) console.log(res)}).then(function(res){console.log(res)})?
轉(zhuǎn)載于:https://www.cnblogs.com/xweizi/p/10089876.html
總結(jié)
以上是生活随笔為你收集整理的浅谈promise用es5实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 12/7个人站立会议
- 下一篇: c. Litmxs找女友