码迷,mamicode.com
首页 > 其他好文 > 详细

promise的学习心得记录

时间:2017-08-28 00:53:30      阅读:317      评论:0      收藏:0      [点我收藏+]

标签:cat   end   syn   com   原理   自动   编程   var   dev   

这里只讲promise,和async的使用方法,不会讲他们的原理。

Promise 是异步编程的一种解决方案,可以用于取代传统的回调函数,该变那些函数层层嵌套调用的尴尬局面。

1)promise

基本语法:

var p= new Promise(function(resolve,reject){
  if(....) resolve();
       else reject(.....);
});

p.then(function(){//resolve
  .......
}).catch(function(){//reject
  .........
});

基本意思就是:每一个promise都有两种状态(对应着请求的pending->fulfiled,pending---->rejected) 

pending->fulfiled:表示成功,执行then()的第一个回调函数

pending-->rejected失败,执行then()的第二个回调函数,一般我们更习惯用catch();更周全

demo01:使用vue,axios,promise演示一下promise到底是啥???

首先在组件中定义了一个getList()

getList(){
     const self=this;
     let promise=new Promise(function(resolve,reject){
                    /*
                    resolve((function(){
                         axios.get(‘./dataAction.php‘).then(function(res){
                          self.list=res.data;
                     
                        }).catch(function(error){});
                        return self.list 
                    })());
                    */
          axios.get(./dataAction.php).then(function(res){
         self.list=res.data;
         resolve(res.data);
        }).catch(function(error){});
                    
     });

       promise.then(function(res){
      console.log("我要等待axios请求之后再执行");
      console.log(res);
     }).then(function(){
});

 

在组件挂在之后就会触发这个方法,

mounted(){
  this.getList();
  //this.countMethod();
}

为了演示出效果我在php代码中做了延时处理:(目的是为了延时四秒之后返回结果,这样前端就是一个漫长的等待过程)

<?php
     $dsn="mysql:dbname=vue;host=127.0.0.1";
    $user="root";    
    $password=‘‘;
    $db= new PDO($dsn,$user,$password);
    $sta= $db->prepare("select * from res");
     $sta->execute();
     $arr=array();
     while($row=$sta->fetch(PDO::FETCH_ASSOC)){
         //print_r($row);
         
         $arr[]=$row;
     }
     $interval=4;
      sleep($interval);
     print_r( json_encode($arr));  
?>

你会发现确实过了四秒中上面那两句红色的才执行。。。。。。。。

 

既然现在框架ajax一般都有的自己promise,那我们何必要学习了??

现在我的需求是,有三个很普通函数,不涉及到请求,这三个函数都有一个延迟函数settimeout,返回一个数字,另外还有一个函数用于接受他们的返回参数,进行相加,返回结果??

按照我们的理解settimeout会在主程序执行完之后才执行,这样我们根本就不能获得相加的结果

demo02:

function mycount1(){           
      let a=4;
      setTimeout(()=>{ return a;},1000);
//resolve(a);
},
function mycount2(){ let b
=6; setTimeout(()=>{resolve(b);
},5000); }, function countAll(a,b){
  return a+b;
} var a=mycount1();
var b=mycount2();
countAll(a,b);

 

技术分享

现在我们有了promise,那么这一切就好说了

因为有多个执行过程,这个时候我想到了promise.all([......]).then();

语法作用就是all([.....])中可以有多个promise对象,等他们都执行成功之后才会触发后面的then(),,[前提是都执行成功之后]


function mycount1(){
  return new Promise(function(resolve,reject){
  let a=4;
  setTimeout(()=>{resolve(a)},1000);
  //resolve(a);
});

  /*
    return Promise.resolve((function(){
    setTimeout(()=>{return 4},4000);

    })())
  */
};

function mycount2(){
  let b=6;
  return new Promise(function(resolve,reject){
  setTimeout(()=>{resolve(b);},5000); });
};

function countAll(a,b){
  console.log("我是最后执行的");
  console.log(a+b);
};

const m1=mycount1().then((a)=>{console.log(a); return a;});
const m2=mycount2().then((b)=>{console.log(b); return b;});

//此时m1,m2都是promise对象
Promise.all([m1,m2]).then(function([a,b]){
  countAll(a,b);
});

技术分享

这里在给一个promise.all([])的例子

    getList3(){
      const self=this;
      const a1=axios.get(./dataAction.php);//axios请求之后返回一个promise
      const a2=axios.get(./dataAction.php);//axios请求之后返回一个promise  
                //两个promise返回两个参数,因此我们就用数组接受参数(如果只用一个参数接受,他会自动变成一个数组)
                //首先promise.all的参数是promise数组集合
      Promise.all([a1,a2])
             .then(([r1,r2]) => {
               console.log(r1);
            //    let arr=[];
           //arr.push(...r1);
            console.log(r2);
     });
},

mounted(){
  //this.getList();
  //this.countMethod();
  this.getList3();
}


技术分享

讲了这么多不是为了好玩,在项目中我们是不是有很多情况下,是需要在某一个函数执行完之后再执行另一个函数的,

例如页面的加载完之后,或者dom树加载完之后,当然学过js的同学知道,页面加载有一个document.readyState的几个状态

https://developer.mozilla.org/zh-CN/docs/Web/API/Document/readyState

技术分享

然后就有了我们经常用的

1)网站所有的资源都加载完毕才执行

window.onload=function(){};

2)dom树加载完之后执行,先于window.onload;

$(function(){});//或者$(document).ready(function(){......});

 

当然promise还有其他的api,你可以google自己学习下,

例如:Promise.resolve(.....)可以将一个非promise对象包装成一个promise,这样就可以使用then方法了

 

promise的学习心得记录

标签:cat   end   syn   com   原理   自动   编程   var   dev   

原文地址:http://www.cnblogs.com/evaling/p/7440871.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!